一个循环中的不同扫描仪数据类型。该怎么办?

时间:2017-04-05 23:31:13

标签: java

背景:这是一个简单程序的最后一个循环,用户首先输入任意数量的整数(双)命令行参数,然后我把它们放在一个长度为[args.length]的数组中,然后我允许用户输入任何整数并检查它是否在数组中。我希望循环结束,程序只在用户输入字符串"退出"时才终止。

但我不知道该怎么做。当然,要解决这个问题太难了。 (PS我一开始就制作了一个静态扫描仪方法,所以我的问题不在于计算机的问题是你不能两次打电话给同一个先生stdin,白痴!'。)

isWinner: true

我需要用户能够输入数字或单词"退出"。我怎么能在循环中做到这一点?

3 个答案:

答案 0 :(得分:1)

如果您需要用户能够在单个输入中输入多种类型的数据,请将其作为字符串抓取,然后解析它以确定您实际获得的数据类型。

假设您的方案是用户可以输入数字或单词"退出"。任何其他输入无效。

首先,捕捉用户给你的任何东西 - 字符串,数字,等等:

String input = stdin.nextLine();

然后尝试将其解析为您的用例:

if("exit".equalsIgnoreCase(input)) {
    // user entered exit
    System.exit(0);
}

// Check to see if it's a number. There's a number of ways to do this, but for simplicity's
// sake, we'll just try to parse it.
try {
    Double number = Double.parseDouble(input);
    // do something here with number;
} catch (NumberFormatException e) {
    // it was not a double, whatever it was.
    // put some error handling here, maybe a message about a bad/unrecognized input
}

请注意,检查这样的数据类型被认为是不好的做法(例如,如果失败,尝试解析然后捕获异常。)我只是在这里做这个技术的例子。

答案 1 :(得分:1)

你怎么读一次,然后解析?

while (true) {
    String userstdin = stdin.nextLine();
    if (userstdin.equals("exit")) {
      System.out.println("Terminating.");
      return;
    }

    double d = Double.parseDouble(userstdin);
    if (contains(arguments, d)) {
      System.out.println("This number is in your array.");
    } else {
      System.out.println("This number is not in your array.");
    }
}

或者,更简洁

double d = Double.parseDouble(userstdin);
String in = contains(arguments, d) ? "is" : "is not";
System.out.printf("This number %s in your array.\n", in);

注意:try-catching Double.parseDouble是个好主意

答案 2 :(得分:0)

简单:您可以先检查用户提供的字符串是否为equalIgnoreCase()为"退出"。

如果不是,则在该字符串上调用Integer.parseInt()。如果该调用没有抛出异常,则输入实际上是一个数字。