java - 我可以使用同一个扫描仪来扫描 double 型和字符串型吗?这个 "||"是一个 or 语句吗?

标签 java string if-statement while-loop java.util.scanner

    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 声明为一个字符串,它存储下一个用户输入的字符串的内容,该字符串将使用 newItemPriceSC 进行扫描。我使用相同的扫描仪来扫描 newItemPrice,一个 double 值,它执行正常。

请注意,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.

问号后面的是如果评估结果为 true 会发生什么;

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

冒号后面的是返回 false 时会发生的情况,即 !answ.matches("\\d*");

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

关于java - 我可以使用同一个扫描仪来扫描 double 型和字符串型吗?这个 "||"是一个 or 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976093/

相关文章:

java - 无法使用 Morphia 连接到 MongoDb

java - 如何使用 printf() (Java) 正确格式化文本

c++ - 重置字符串流

javascript - 对包含数字和字符串的数组进行排序

string - Perl 5 何时获得 Copy-On-Write 字符串?

php - if else 在 $_post isset 内

java - 保存和删除按钮不起作用

c# - Android和C#之间的加密兼容

php - 为 Sql 表中的每一行循环一个 If 语句

Python:需要一个缩进 block