java 当使用hasNextDouble()验证价格输入时,它会打印“Invalid Input”,然后才要求输入[关闭]

rryofs0p  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(50)

已关闭。此问题需要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:


编辑:如前所述,添加了一个最小可重现示例。

s3fp2yjn

s3fp2yjn1#

如果你坚持使用Scanner#next()而不是Scanner#nextLine(),那么你可以这样声明你的Scanner:

Scanner input = new Scanner(System.in).useDelimiter("\\R");

字符串
由于productName中可能有空格,.useDelimiter("\\R")将使next()将整个条目带到换行符。next() * 通常 * 用于检索空格分隔的字符串标记(但不总是)。我个人更喜欢使用Scanner#nextLine()用于所有控制台提示。
不需要多次输出提示符。将提示符放在while循环中就足够了:

Scanner input = new Scanner(System.in).useDelimiter("\\R");

// Get price of product
String priceStrg = "";
while (priceStrg.isEmpty()) {
    System.out.print("\nEnter Product Price: -> ");
    priceStrg = input.next().trim(); 
    /* If you use `nextLine()` above instead of `next()` then 
       you can get rid of `.useDelimiter("\\R")`.    */
        
    /* Validates that a string representation of a signed 
       or unsigned Integer or floating point value was
       actually supplied.            */
    if (!priceStrg.matches("-?\\d+(\\.\\d+)?")) {
        System.out.println("Invalid Entry! (" + priceStrg 
                + ") - Try again..." + System.lineSeparator());
        priceStrg = ""; // Empty prompt input variable to ensure re-loop.
    }
}
    
/* If we make it to this point then entry was valid!
   Convert `priceStrg` to a double type and store
   within the `productPrice` double type variable: */
double productPrice = Double.parseDouble(priceStrg);


带有Regular ExpressionString#matches()方法用于验证User条目。表达式的作用是确保User提供的条目字符串只不过是一个有符号或无符号整数或浮点值的字符串表示。

busg9geu

busg9geu2#

这个问题围绕着使用正确的方法接受输入。
使用Scanner类的nextLine()方法从用户那里获取一个字符串。nextLine()方法读取文本直到行尾。阅读行尾后,它将光标扔到下一行。

System.out.print("\nEnter Product Name: ");
String productName = input.nextLine();

字符串

相关问题