【问题标题】:Can I use the same scanner to scan a double and string? Is this "||" an or-statement?我可以使用同一个扫描仪来扫描双精度和字符串吗?这是“||”吗或语句?
【发布时间】:2015-05-12 14:54:42
【问题描述】:
    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")

【问题讨论】:

  • 您在运行此程序时发现了什么?您是否在运行时检查了变量以查看它们所包含的内容?
  • @Patrick,当打印“输入商品价格”时,我输入“不再”。然后它将显示“主线程中的错误”以及另外几行错误文本。我没有在运行时检查变量
  • 我相信在问题中添加错误文本将有助于社区帮助您了解您的问题。很难从“它没有按照我想要的那样工作”来猜测错误。

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


【解决方案1】:

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

    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

冒号后面的内容是如果返回false会发生什么,即!answ.matches("\\d*");

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

【讨论】:

  • 您收到 InputMismatchException 的原因可能是因为您在尝试读取 Double 时输入了一个非数字值。您还需要修改匹配中的正则表达式以适应小数。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 2019-10-22
  • 2023-04-11
  • 2010-09-20
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多