【问题标题】:java.lang.NumberFormatException: For input string: "23 " [duplicate]java.lang.NumberFormatException:对于输入字符串:“23” [重复]
【发布时间】:2015-04-19 14:53:21
【问题描述】:

我给了 23(看起来像一个正确的字符串)作为输入,但仍然得到 NumberFormatException。请指出我哪里出错了。

PS 我试图解决 codechef 上的“厨师和字符串问题”

相关代码:

Scanner cin=new Scanner(System.in);
      cin.useDelimiter("\n");
      String data=cin.next();
      System.out.println(data);

      /*
       * @param Q no. of chef's requests
       */
      String tempStr=cin.next();
      System.out.println(tempStr);;
      int Q = Integer.parseInt(tempStr);

输出:

sdfgsdg
sdfgsdg

23
23

Exception in thread "main" java.lang.NumberFormatException: For input string: "23
"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Chef.RegexTestHarness.main(RegexTestHarness.java:24)

完整的程序:

package Chef;
//
//TODO codechef constraints
import java.util.Scanner;
import java.lang.*;
import java.io.*;

//TODO RETURN TYPE
class RegexTestHarness
{
  public static void main(String args[])
  { 

      Scanner cin=new Scanner(System.in);
      cin.useDelimiter("\n");
      String data=cin.next();
      System.out.println(data);

      /*
       * @param Q no. of chef's requests
       */
      String tempStr=cin.next();
      System.out.println(tempStr);;
      int Q = Integer.parseInt(tempStr);

      for(int i=0; i<Q; i++)
      {
          /*
           * @param s chef's request
           */
           String s= cin.next();//request

//void getParam() (returning multiple parameters problem)
   //{a b L R
   //where a:start letter
   //b: end lettert
    //L: minStartIndex
    //L<=S[i]<=E[i]<=R
           //R is the maxEndIndex

//TODO transfer to main

    char a=s.charAt(0);
    char b=s.charAt(3);
    int L=0, R=0;
    /*
     * @param indexOfR in the request string s, we separate R (which is maxEndIndex of chef's
     * good string inside data string)
     * . To do that, we first need the index of R itself in request string s 
     */
    int indexOfR= s.indexOf(" ", 5) +1;
    System.out.println("indexOfR is:" + s.indexOf(" ", 5));

    L= Integer.parseInt( s.substring(5, indexOfR - 2) );
    //TODO check if R,L<10^6

    R=Integer.parseInt( s.substring(indexOfR) );

    //}  ( end getparam() )
  //-----------------------------------
    //now we have a b L R

    //String good="";
    //TODO add other constraints (like L<si.....) here
    if(a !=b)
    {   int startInd=data.indexOf(a, L), endInd=data.lastIndexOf(b, R);
    int output=0, temp;

    while((startInd<endInd)&&(startInd != (-1) ) && ( endInd != (-1) ))
        {

          temp = endInd;
            while((startInd<endInd))
            {


            //good= good+ s.substring(startInd, endInd);
            output++;


            endInd=data.lastIndexOf(b, endInd);
            }
            startInd=data.indexOf(a, startInd);
            //TODO if i comment the line below, eclipse says tat the variable temp 
            //(declared at line 68) is not used. Whereas it is used at 68 
            //(and 83, the line below) 
            endInd=temp;

        }
    System.out.println(output);

    }





      }//end for


  cin.close();
  }


}

【问题讨论】:

    标签: java string numberformatexception parseint


    【解决方案1】:

    您的字符串有一个尾随空格。

    int Q = Integer.parseInt(tempStr.trim());
    

    【讨论】:

      【解决方案2】:

      使用Scanner.nextInt(),避免解析字符串。

      Scanner.hasNextInt()这个方法也很有用。

      【讨论】:

        【解决方案3】:

        查看异常的结束双引号" - 它位于下一行,这意味着输入字符串的末尾有'\n''\r'

        您可以通过在将字符串传递给解析方法之前调用trim() 来解决此问题,但您最好让next() 使用系统特定的行分隔符为您去除行尾字符,例如这个:

        cin.useDelimiter(System.lineSeparator());
        

        或通过调用hasNextInt/nextInt 让扫描仪进行转换。

        【讨论】:

          【解决方案4】:

          这是我对此类问题的标准答案:

          Exception in thread "main" java.lang.NumberFormatException: For input string: "23
          "
          at java.lang.NumberFormatException.forInputString(Unknown Source)
          at java.lang.Integer.parseInt(Unknown Source)
          at Chef.RegexTestHarness.main(RegexTestHarness.java:24)
          

          意思是:

          There was an error. We try to give you as much information as possible
          It was an Exception in main thread. It's called NumberFormatException and has occurred for input "23\n".
          which was invoked from method main in file RegexTestHarness.java in line 24.
          

          换句话说,您试图将"23\n" 解析为int,这是Java 无法使用方法Integer.parseInt 完成的。 Java 提供了漂亮的堆栈跟踪,它可以准确地告诉您问题所在。您正在寻找的工具是 debugger,使用 breakpoints 可以让您在选定的时刻检查您的应用程序的状态

          如前所述,在解析为 int 之前使用 tempStr.trimm() 是安全的。

          【讨论】:

            【解决方案5】:

            如果解析为整数,则输入字符串必须是有效的整数值,没有小数、空格、换行符或任何其他字符。因此,如果包含任何其他字符、小数、空格/换行符,请确保引发异常的输入字符串是否为有效整数,然后尝试将其删除。

            【讨论】:

              猜你喜欢
              • 2017-09-02
              • 2013-09-16
              • 2020-03-11
              • 2018-06-08
              • 1970-01-01
              • 1970-01-01
              • 2012-12-05
              • 2013-09-04
              • 1970-01-01
              相关资源
              最近更新 更多