提问人:coolkid9090 提问时间:3/20/2021 更新时间:3/20/2021 访问量:382
扫描仪输入循环,直到回车或按键
scanner input loop until enter or keypress
问:
我正在创建一个 java 程序,它要求用户输入 2 个输入,第一个输入是分子,第二个输入是分母。例如,如果我写 10 5(用户按回车键),那么答案将是 2,因为 10/5 = 2。
我还希望能够编写几个输入,例如:10 5 20 4 30 5(用户按回车键) 那么答案将是 2、5、6。 如果我写 10 5 20(用户按回车键) 那么答案只有 2,第三个输入是 disgard。
这是我的代码:
public class test {
private static Scanner userpress = new Scanner(System.in);
public static void main(String[] args) {
int choice = 1;
int r;
int h;
System.out.println("---------------------------------");
System.out.println("write your two numbers (numerator, denominator)");
while (userpress.hasNextInt()) {
userpress.useDelimiter("\\s");
r = userpress.nextInt();
h = userpress.nextInt();
userpress.nextLine();
int x = r / h;
System.out.println(x);
}
System.out.println("user dont want play more!")
}
}
当我写 10 5 20 5 我得到输出 2。但我想得到输出 2、4。如果我写 10 5 20 5 30 6,我想得到输出 2、4、5。我该怎么做?如果用户写 10 5 20 5 e,那么我希望输出是 2、4,用户不想玩更多!
答:
0赞
g.momo
3/20/2021
#1
循序渐进:
-
- 只需在 while 循环之前获取分隔符即可。
-
- 删除 nextLine()。
-
- 如果您需要其他改进,请告诉我们(例如退出程序)。
userpress.useDelimiter("\\s"); // here
while (userpress.hasNextInt()) {
// userpress.useDelimiter("\\s"); // remove
if(userpress.hasNextInt()) // for uneven values
r = userpress.nextInt();
if(userpress.hasNextInt()) // for uneven values
h = userpress.nextInt();
//userpress.nextLine(); // remove
int x = r / h;
System.out.println(x);
// for "e"
if( !userpress.hasNextInt() && userpress.hasNextLine()) { // if input is not integer and exists
message();
/*String e =*/ userpress.nextLine(); // clean the cache
}
}
评论