gpt4 book ai didi

java - Java-Scanner .nextLine()读取未分配的字符串

转载 作者:行者123 更新时间:2023-12-02 01:11:46 29 4
gpt4 key购买 nike

我试图输入仅包含特定字符和空格的输入。
问题在于扫描程序正在读取非分配字符串,从而迫使其循环。但是它只会发生/循环一次。
如何停止“第一循环”?

我尝试了input_nome = input.next()
但是,这种方式不会让空格继续输入。
我需要留空格。

public static final Scanner input = new Scanner(System.in);

int age = input.nextInt(); // This is the source of the problem!

System.out.print("Name: ");
String input_nome;
while (true) {
try {
input_nome = input.nextLine();
if (input_nome.matches("[a-zA-Z ]+")) {
break;
} else {
System.err.print("Insert again: ");
}
} catch (Exception e) {
}
}


我希望此输出“名称:”

但是实际的输出是这个“名称:再次插入:”



问题解决了!

以前使用 input.nextInt()时,会发生此问题。

(我没有在问题上提到此,因为我认为这无关紧要)

只需使用 input.nextLine()即可使用\ n字符。像这样:

...
System.out.print("Name: ");
String input_nome;
input.nextLine // This clears the \n character
while (true) {
...


说明: https://stackoverflow.com/a/7056782/11860800

最佳答案

问题解决了!

以前使用input.nextInt()时,会发生此问题。

(我没有在问题上提到此,因为我认为这无关紧要)

只需使用input.nextLine()即可使用\ n字符。像这样:

...
System.out.print("Name: ");
String input_nome;
input.nextLine // This clears the \n character
while (true) {
...


说明: https://stackoverflow.com/a/7056782/11860800

关于java - Java-Scanner .nextLine()读取未分配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57682220/

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