已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。
2天前关闭。
Improve this question的
所以我有一个java程序,它要求用户将产品添加到系统中。当验证产品的价格时,我收到的输出是:
Enter Product Price:
Enter Number of Available Items:
字符串
它似乎每次都跳过产品价格字段,转到“可用产品数量:”字段。
这是我对输入进行验证的实现。
编辑:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// double productPrice = 0.0;
System.out.print("\nEnter Product Name: ");
String productName = input.next();
// System.out.println();
System.out.print("\nEnter Product Price: ");
// Check if the price input is a valid double/int
while (!input.hasNextDouble()) {
// System.out.flush();
System.out.print("\nInvalid input");
input.nextLine();
System.out.print("\nEnter Product Price: ");
}
double productPrice = input.nextDouble();
System.out.print("\nEnter Number of Available Items: ");
int noOfAvailableItems = input.nextInt();
}
}
型
在对不同的输入进行了几次测试之后,我发现了一些令人困惑的行为。
当我输入一个没有空格的值作为产品名称时,价格字段显示为要求输入预期的方式。
Enter Product Name: iphone13
Enter Product Price: 99.00
型
然而,在这方面,
对于像iPhone 13这样带有空格的输入,它完全跳过了产品价格字段。我不知道这可能是什么原因。
Enter Product Name: iphone 15
Enter Product Price:
Enter Number of Available Items:
型
上面只是我代码中的一小部分,因为这是为了一个任务而做的。
我已经尝试了几种不同的验证方法,但似乎没有一种可以解决这个问题。
do {
input.nextLine();
System.out.println("Invalid input");
System.out.print("\nEnter Product Price: ");
} while (!input.hasNextDouble());
double productPrice = input.nextDouble();
型
这是我尝试的另一种方法,但这次我的输出是:
Enter Product Price: Invalid input
Enter Product Price:
型
编辑:如前所述,添加了一个最小可重现示例。
2条答案
按热度按时间s3fp2yjn1#
如果你坚持使用Scanner#next()而不是Scanner#nextLine(),那么你可以这样声明你的Scanner:
字符串
由于productName中可能有空格,
.useDelimiter("\\R")
将使next()
将整个条目带到换行符。next()
* 通常 * 用于检索空格分隔的字符串标记(但不总是)。我个人更喜欢使用Scanner#nextLine()用于所有控制台提示。不需要多次输出提示符。将提示符放在
while
循环中就足够了:型
带有Regular Expression的String#matches()方法用于验证User条目。表达式的作用是确保User提供的条目字符串只不过是一个有符号或无符号整数或浮点值的字符串表示。
busg9geu2#
这个问题围绕着使用正确的方法接受输入。
使用Scanner类的nextLine()方法从用户那里获取一个字符串。nextLine()方法读取文本直到行尾。阅读行尾后,它将光标扔到下一行。
字符串