gpt4 book ai didi

java - 不要求输入

转载 作者:搜寻专家 更新时间:2023-11-01 02:16:29 26 4
gpt4 key购买 nike

我有这个:

Scanner input = new Scanner ( System.in );
int selection = input.nextInt();
if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();
}

但是,当到达请输入字符串时,它不会要求任何输入。它只是转到程序的其余部分。

最佳答案

ScannernextInt() 处等待,直到用户按下回车键。发生这种情况时,它会消耗数字,但不会换行符本身。因此,对 nextLine() 的下一次调用会立即返回一个空的 String 作为结果。

这应该可以解决:

int selection = input.nextInt();
input.nextLine();
if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();

但我的首选方法是始终使用 nextLine 并单独进行解析:

String selectionStr = input.nextLine();

//consider catching a NumberFormatException here to handle erroneous input
int selection = Integer.parseInt(selectionStr);

if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();
//...

关于java - 不要求输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com