【问题标题】:Ensure user input = String, not int type确保用户输入 = String,而不是 int 类型
【发布时间】:2016-11-14 01:51:02
【问题描述】:
public static void main(String[] args) {
    // Create a new Scanner object to obtain 
    System.out.println("Please enter the word you are looking for");
    // input from System.in
    Scanner input = new Scanner(System.in);
    String userin  = input.next();

我的目标是编写一个循环来分析用户的输入,以确保它是一个String,它不代表int。如果是 int 那么我希望返回一个错误信息

【问题讨论】:

  • All 输入将是字符串。它们可能是带有数字的字符串,但这仍然是一个字符串。
  • input.next 返回一个字符序列。因此,根据定义,它始终是String。如果他们输入 12345,则结果将是 String,其中包含五个字符 '1''2''3''4''5'。如果你想禁止输入,除非它们包含至少一个字母(或类似的东西),这是可以做到的。但我认为首先你需要克服对类型的困惑。
  • 我们需要在这里澄清一下.. input.next() 获取字符串。但是你如何定义“int”?你是把它定义为“仅限数字”还是java中的“int”数据类型?
  • andymancan,我的回答对您有帮助吗?如果需要,请要求澄清。

标签: java loops java.util.scanner


【解决方案1】:
  1. 每个输入都是String,因为Strings 也可能代表数字字符序列。
  2. 您可以使用正则表达式验证输入。

以下代码应该会有所帮助:

String userin  = input.next();
if (userin.matches("[0-9a-zA-Z]*[a-zA-Z]+[0-9a-zA-Z]*")) {
    //input contains only small and large letters. At least one character.
} else {
    throw new RuntimeException("The input must be single word and mustn't contain digits only");
}

【讨论】:

    【解决方案2】:

    正如其他人所说,每个输入都是一个字符串。如果您想拒绝仅由数字字符组成的字符串,例如“1234”,您可以通过几种不同的方式检查它是否是整数 - 可能循环遍历字符串并在每个字符上调用 isDigit(),或者将字符串传递给 parseInt 并捕获 NumberFormatException。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2022-01-13
      • 2012-10-02
      • 2017-02-25
      • 1970-01-01
      • 2021-09-08
      • 2012-02-07
      相关资源
      最近更新 更多