Java Object Array, asking for two different inputs? -
so here test class:
import java.util.scanner; public class test { public static void main (string[] args){ film[] f = new film[10]; scanner input = new scanner(system.in); (int i=0;i<10;i++){ f[i] = new film(); system.out.println("enter title:"); f[i].settitle(input.nextline()); system.out.println("enter film length:"); f[i].setlength(input.nextdouble()); } } }
i have getter , setter methods in object class film. problem here output comes out as:
enter title: title1 enter film length: 1 enter title: enter film length: 2 enter title: enter film length: 3 enter title: enter film length:
how fix code asks 10 user inputted titles , lengths , @ end display film titles , lengths?
thanks.
*i have tostring method:
public string tostring(){ return "title: "+title+" length: "+length; }
your code skips ask titles after 2 iterations because use nextline() titles. have use next() in case.
in code, if first input.nextdouble() receives, example,
1\n
then, nextdouble() takes value "1" , "\n" passed nextline() of second iteration.
finally, nextline() reads "\n" new line, , nextdouble() executed in second iteration , after.
the whole revised code follows.
import java.util.scanner; public class test { public static void main (string[] args){ film[] f = new film[10]; scanner input = new scanner(system.in); (int = 0; < 10; i++){ f[i] = new film(); system.out.println("enter title:"); f[i].settitle(input.next()); system.out.println("enter film length:"); f[i].setlength(input.nextdouble()); } input.close(); (int = 0; < 10; i++) { system.out.println(f[i]); } } } class film { private string title; private double length; public film() { } public void settitle(string title) { this.title = title; } public void setlength(double length) { this.length = length; } public string tostring() { return "title: "+title+" length: "+length; } }
Comments
Post a Comment