gpt4 book ai didi

java - 用逗号扫描字符串

转载 作者:行者123 更新时间:2023-11-29 03:56:16 26 4
gpt4 key购买 nike

我用 system.in 创建了一个 Scanner

如何允许输入中包含逗号而不转到下一个输入?

例如:

System.out.print("Enter City, State.");
String location = scan.nextLine();

我无法输入city,state,因为语言认为我想继续下一个扫描输入问题。如何允许在扫描字符串中使用逗号?

*完整代码

扫描仪scan1 = new Scanner (System.in);

System.out.print ("City, State: ");
String location1 = scan.nextLine();

System.out.print ("Enter number: ");
number1 = scan.nextDouble();

System.out.print ("Enter number: ");
number2 = scan.nextDouble();

System.out.print ("City, State: ");
String name2 = scan1.nextLine();

System.out.print ("Enter #: ");
number3 = scan.nextDouble();

System.out.print ("Enter #: ");
number4 = scan.nextDouble();

最佳答案

scan.nextLine(); 将返回整行,逗号与否。

如果不是这样,则问题一定出在其他地方,您应该提供更多代码。

回复:完整代码:仍然有效。您遇到的错误/不良行为是什么?

我认为正在发生的事情是 nextLine() 正在捕获您之前输入的行尾字符。

发生了什么:

  • 假设您输入一个数字,如 12.5 并按 enter
  • Scanner 从中读取的缓冲区现在包含 12.5\n,其中 \n 是换行符。
  • Scanner.nextDouble 仅读取 12.5 并且 \n 留在缓冲区中。
  • Scanner.nextLine 读取该行的其余部分,即 \n 并返回一个空字符串。这就是它跳到下一个输入的原因:它已经读取了“一行”。

我会做些什么来修复它:

System.out.print ("City, State: ");
String name2;
do{
name2 = scan1.nextLine();
}while( name2.trim().isEmpty() );

此循环的作用是不断读取下一行,直到其中包含除空格以外的内容为止。

关于java - 用逗号扫描字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246237/

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