当我输入第一个输入时,它会同时打印第二个和第三个输入。控制台:
Please enter the grade for course 1
A
Please enter the grade for course 2
Please enter the grade for course 3
代码:
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");
}
}
答案 0 :(得分:6)
System.in.read();
将从用户输入中读取下一个字节。键入数字并按 Enter 时,它将至少计算三个字节(两个附加字节对应\r
和\n
个新行字符。/ p>
您只需使用Scanner
实例并使用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();
}
如果要求System.in.read()
并且作为字符串输入成绩,那么这是一种(有点hacky)方式:
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);
}