My problem is when i run the program it runs all the System.out.print right but when i run it for the second student some of it overlaps like so:
"Enter the second student's name: Enter the student's score: "
instead of
"Enter the second students's name: "
"Enter the student's score: "
I also can not input data into the System.out.print method of the second student
My main 开发者_如何学Ccode where the error is:
System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: ");
score = reader.nextInt();
student1.setScore(i, score);
}
System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
System.out.print("Enter the students's score: "); //program skips to here to input
//data
score = reader.nextInt();
student2.setScore(i, score);
}
the part that deals with the error from the class is as follows
public void setName(String nm){
name = nm;
}
You should call println()
to print a newline character, after reading the input.
If by "overlapping" you mean they appear on the same line then you want System.out.println
, rather than System.out.print
. println
emits a trailing newline.
Could you more clearly describe this 'overlapping'? In your original question your 'one versus the other' were identical. Make it a code sample if need be to preserve spacing and such,
I believe you are talking about how all the lines are printed on the same line. You need to either use line break characters '\n' in Java, or use System.out.println
Try inserting:
reader.nextLine();
...before
System.out.print("Enter the second student's name: ");
.nextInt()
doesn't swallow the newline from your input, so the next call to nextLine()
just gets the newline character and returns you an empty string - and the program continues, printing the next line of output.
If what I understand is right, you may probaly have problems with the input of the java console. I can't tell much because there's not enough information, but maybe you can refer this link for getting input in java console: http://www.abbeyworkshop.com/howto/java/readLine/index.html
And I recommend clearing the un-affected code (about class Student), just check the input & output from console only.
精彩评论