限制 Java 中的输入行数?
Limit number of input lines in Java?
我有一个问题,我想从用户那里获取输入,用户可以插入 1 行,最多 8 行,每行代表一个案例。
我想要的是当用户插入 8 行时停止扫描器,或者如果用户想要少于 8 行,他可以按回车键或特定键来结束循环。
到目前为止我做了什么:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
每行输入两个数字,一个代表i,一个代表j。
输入:
0 0
100 300
99 399
0 200
输出应该是:
C1: 0
C2: 100
C3: 1
C4: 200
希望这能解释我的问题。
提前致谢!
正如@Abhishek 所建议的,您可以使用计数器变量:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}
我有一个问题,我想从用户那里获取输入,用户可以插入 1 行,最多 8 行,每行代表一个案例。 我想要的是当用户插入 8 行时停止扫描器,或者如果用户想要少于 8 行,他可以按回车键或特定键来结束循环。
到目前为止我做了什么:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) { // here I want to check so that it don't exeed 8 lines
int e;
int m;
i = input.nextInt();
j = input.nextInt();
int num = 0;
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
}
}
每行输入两个数字,一个代表i,一个代表j。
输入:
0 0
100 300
99 399
0 200
输出应该是:
C1: 0
C2: 100
C3: 1
C4: 200
希望这能解释我的问题。
提前致谢!
正如@Abhishek 所建议的,您可以使用计数器变量:
public static void doSomthing(){
Scanner input = new Scanner(System.in);
int linesParsed = 0;
while (linesParsed < 8 && input.hasNextLine()) {
// What are you using these variables for? You compute their
// values, but then you do not use them
int e;
int m;
// Where are these variables declared? It seems weird to have
// instance variables be named i and j
i = input.nextInt();
j = input.nextInt();
int num = 0;
// Unless i and j are being modified concurrently somewhere
// else in the code, this will result in an infinite loop
while (i != 0 || j != 0) {
num += 1;
e = (e + 1) % 100;
m = (m + 1) % 400;
}
System.out.println(num);
linesParsed++;
}
}