Reputation: 91
When i put in the first input it prints the second and the third at the same time. Console:
Please enter the grade for course 1
A
Please enter the grade for course 2
Please enter the grade for course 3
Code:
import java.io.IOException;
public class MyGradeLoops {
public static void main(String[] args) throws IOException{
int grade;
for (int i=1; i<6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = System.in.read();
}
System.out.println("Thank your for submitting your grades");
}
}
Upvotes: 1
Views: 82
Reputation: 72854
System.in.read();
will read the next byte from the user input. When you type a number and press Enter, it would count for at least three bytes (with the two additional bytes corresponding to \r
and \n
new line characters).
You can simply use a Scanner
instance and read the integer using Scanner#nextInt()
.
Scanner in = new Scanner(System.in);
for (int i = 1; i < 6; i++) {
System.out.println("Please enter the grade for course " + i);
grade = in.nextInt();
}
If System.in.read()
is a requirement and the grade is input as a string, here's a (sort of hacky) way to do it:
for (int i = 1; i < 6; i++) {
String grade = "";
System.out.println("Please enter the grade for course " + i);
char c;
while((c = (char) System.in.read()) != '\n') {
grade += c;
}
System.out.println(grade);
}
Upvotes: 6