【问题标题】:Using scanner to recognize both integers and strings, and stopping user input if a certain string is inputted [duplicate]使用扫描仪识别整数和字符串,并在输入某个字符串时停止用户输入[重复]
【发布时间】:2020-08-04 08:51:29
【问题描述】:

尝试使用扫描仪识别整数和字符串,如果输入了某个字符串,则停止用户输入。

Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();

需要这样做,如果用户键入“end”,扫描仪将不再接受用户输入。我不能把行 int numberof = myObj.nextInt();在循环或其他东西中并限制变量范围,因为我在我的其余代码中使用 numberof 的值。

【问题讨论】:

  • 如果用户输入“supercalifragilisticexpialidocious”怎么办?提示:你会得到一个例外......

标签: java string integer java.util.scanner


【解决方案1】:

如果需要,您可以使用 Scanner#next 然后解析整数。我不建议直接使用 Scanner#nextInt。

Scanner sc = new Scanner(System.in);
do {
  System.out.println("Enter number of students");
  String next = sc.next();
  if (next.equals("end")) break;
  else {
    try {
      int num = Integer.parseInt(next);
    } catch (NumberFormatException e) {
      System.out.println("Please enter a valid input");
    }
  }
} while (true);

【讨论】:

  • 如果我使用它,在那个场景中,整数 num 的范围将受到限制,我需要在我的代码中访问它。
  • @Kai 你可以随时在外面声明
猜你喜欢
  • 2011-08-23
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2016-08-24
  • 1970-01-01
相关资源
最近更新 更多