Integer.parseInt没有将字符串解析为整数

时间:2015-04-13 04:55:45

标签: java string parsing integer

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)

4 个答案:

答案 0 :(得分:3)

我认为你误解了

的功能
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);
    }

答案 1 :(得分:1)

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

如果您期望字符串并希望将它们转换为int s,则可以分别对输入字符串的每个字符使用Character.getNumericValue(myChar)

答案 2 :(得分:0)

您应该查看Integer.parseInt(String s)

上的文档

正如您所看到的,已解析的String将转换为整数值,如果该值不是整数,则会抛出NumberFormatException

  

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

     

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

答案 3 :(得分:0)

好吧,我发布了我觉得最适合我想要的案例的答案。但是,谢谢大家的帮助。

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