我可以使用同一个扫描仪来扫描双精度和字符串吗?这是“||”吗or 语句?

Can I use the same scanner to scan a double and string? Is this "||" an or-statement?

    System.out.println("\nEnter item's price");
    Scanner newItemPriceSC = new Scanner(System.in);
    Double newItemPrice = newItemPriceSC.nextDouble();//stores item price
    String goBack = newItemPriceSC.nextLine();      

    System.out.println("type \"no more\" if there are no more items\ntype any other word to continue");

    String answ = continueEnd.nextLine();               


    if(!(answ.equals("no more"))){
        continue;//if user does not answer "no more!", loop continues
    }

    if(answ.equals("no more") || goBack.equals("no more")){//if user answers "no more!": 

最后一段代码:

goBack.equals("no more")

不触发 if 语句的内容(未显示)并在我键入 "no more" 时显示以下错误文本:

 Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Ben_Li_CashRegisterProgram.main(Ben_Li_CashRegisterProgram.java:64)

我在上面将goBack 声明为一个String,它存储了下一个用户输入的String 的内容,这些内容将被newItemPriceSC 扫描。我使用相同的扫描器来扫描 newItemPrice,一个双精度的,它执行正确。

请注意,if 语句的第一部分确实执行了 if 语句的内容:

(answ.equals("no more")

建议的改进,但可以进一步重构;

    System.out.println("\nEnter item's price");
    Scanner newItemPriceSC = new Scanner(System.in);

    while (true) {
        System.out.println("Please type \"no more\" if there are no more items");
        String answ = newItemPriceSC.nextLine();
        if (!answ.equalsIgnoreCase("no more")) {
            System.out.println(answ.matches("\d*") ? "Item price: " + answ : "Please enter a numerical value");
        } else {
            break;
        }
    }

如果您想知道以下行的作用;

System.out.println(answ.matches("\d*") ? "Item price: " + answ : "Please enter a numerical value");

这使用了一种叫做三元运算符的东西。它相当于一个 if else 语句。

answ.matches("\d*") //This is evaluating whether the string matches any digit. This returns true or false.

问号后面是如果计算结果为真会发生什么;

? "Item price: " + answ // This is what will happen if it returns true

冒号后面是returns false时会发生什么,即!answ.matches("\d*");

: "Please enter a numerical value" // This is what will happen if it returns false