For循环前进两个数而不是一个

时间:2014-10-16 19:16:07

标签: java loops for-loop

当我输入第一个输入时,它会同时打印第二个和第三个输入。控制台:

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");
   }
  }

1 个答案:

答案 0 :(得分:6)

System.in.read();将从用户输入中读取下一个字节。键入数字并按 Enter 时,它将至少计算三个字节(两个附加字节对应\r\n个新行字符。

您只需使用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);
}