【问题标题】:Integer.parseInt not parsing a string into integerInteger.parseInt 不将字符串解析为整数
【发布时间】:2015-06-18 08:04:52
【问题描述】:
Scanner sc = new Scanner(System.in);
length = sc.nextLine();
length_to_play = Integer.parseInt(length);

我尝试使用 length.trim() 和 length.replaceAll() 来丢弃空格,但没有奏效。 我在线程“main”java.lang.NumberFormatException 中有异常。

Exception in thread "main" java.lang.NumberFormatException: For input string: "y"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at speedwords.first_activity(speedwords.java:27)
    at speedwords.main(speedwords.java:338)

【问题讨论】:

  • 你有什么错误吗?
  • @ArhatBaid 发布完整的堆栈跟踪,它也会显示字符串。
  • 是的.. 每当我输入一个字符时,我都会得到一个“主要”java.lang.NumberFormatException。
  • @ArhatBaid 您输入的字符或数字
  • 我正在尝试输入一个整数,但是每当输入一个字符时,应该向用户显示一条打印消息(我使用的是 if-else)。但是在输入一个字符时,就会出现这个错误。

标签: java string parsing integer


【解决方案1】:

我想你误解了

的功能
Integer.parseInt();

来自 Java 文档

  Parses the string argument as a signed decimal integer. The 
  characters in the string must all be decimal digits, except that 
  the first character may be an ASCII minus sign <code>'-'</code> 
  (<code>'&#92;u002D'</code>) to indicate a negative value. The resulting 
  integer value is returned, exactly as if the argument and the radix 
  10 were given as arguments to the 
  {@link #parseInt(java.lang.String, int)} method.

  @param s       a <code>String</code> containing the <code>int</code>
              representation to be parsed
  @return     the integer value represented by the argument in decimal.
  @exception  NumberFormatException  if the string does not contain a
                parsable integer.
public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
    }

【讨论】:

  • 但是 parseInt() 不应该返回字符串的 ASCII 整数值吗?
  • @ArhatBaid 寻找内部实现,你会得到所有答案
【解决方案2】:

当用户输入数字时,你应该使用sc.nextInt()。这样你就不需要自己编写解析了。

如果您需要字符串并希望将它们转换为ints,您可以在输入字符串的每个字符上单独使用Character.getNumericValue(myChar)

【讨论】:

  • 如果我使用 sc.nextInt () ,那么如何使用 IF-ELSE 块向用户打印消息?我希望在输入一个字符时我可以将它转换为它的 ASCII 整数值并检查 IF 块
  • 好的,您可能需要编辑问题以提及您要专门转换字符。
  • 但是一个字符不也是一个可能的字符串吗?即使我输入,例如“tyf”的字符串,parseInt() 也不会返回 ASCII 整数值。
  • 不,它不是这样工作的。作为“tyf”的 int 结果,您期望什么?其字符的 ASCII 值的总和还是作为字符串的值的串联?我已经编辑了我的答案。
【解决方案3】:

你应该看看Integer.parseInt(String s)上的文档

如您所见,解析后的 String 被转换为整数值,如果该值不是整数,则抛出 NumberFormatException

为什么你期望它应该返回 ASCII 整数值?

答案:我们传递的是字符串,而不是具有独立 ASCII 值的char。如果您想要字符串中每个字符的 ASCII,那么您可以查看此question

【讨论】:

  • 是的,这就是我最终以不同的方式所做的。
【解决方案4】:

好的,我正在发布我认为最适合我想要的案例的答案。不过谢谢大家的帮助。

Scanner sc = new Scanner(System.in);
length = sc.nextLine();
//length_to_play = Integer.valueOf(length); didn't work
char ch = length.charAt(0);
length_to_play=Character.getNumericValue(ch); //worked

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    相关资源
    最近更新 更多