java.lang.NumberFormatException:对于输入字符串:“23”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28586430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:28:35  来源:igfitidea点击:

java.lang.NumberFormatException: For input string: "23 "

javastringnumberformatexceptionparseint

提问by gnsb

I gave 23 (looks like a proper string) as input, but stil get NumberFormatException. Please point out where I went wrong.

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

PS I was trying to solve "chef and strings problem" on codechef

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

Relevent code:

相关代码:

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);

Output:

输出:

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)

Complete program:

完整程序:

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();
  }


}

采纳答案by Eran

Your String has a trailing white space.

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

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

回答by Paco Abato

Use Scanner.nextInt()and avoid to parse the String.

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

Also it's useful the method Scanner.hasNextInt().

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

回答by dasblinkenlight

Take a look at the closing doublequote "on the exception - it is positioned on the next line, meaning that the input string has '\n'or '\r'at the end.

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

You can fix this by calling trim()before passing the string to the parsing method, but you would be better off having next()strip the end-of-line character for you by using system-specific line separator, like this:

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

cin.useDelimiter(System.lineSeparator());

or by calling hasNextInt/nextIntto let the scanner do the conversion.

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

回答by A.Aleem11

Input String if parsed as integer then its must be valid integer value no decimal, space, line-break or any other character. So make sure The Input String throw in exception is valid integer or not if contain any other character, decimal, space/line-break then try to remove that.

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

回答by xenteros

It's my standard answer to such questions:

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

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)

means:

方法:

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.

In other words, you tried to parse "23\n"to an intwhat Java can't do with method Integer.parseInt. Java has provided beautiful stacktrace which tells you exactly what the problem is. The tool you're looking for is debuggerand using breakpointswill allow you to inspect the stateof you application at the chosen moment.

换句话说,您尝试解析"23\n"intJava 无法使用 method 执行的操作Integer.parseInt。Java 提供了漂亮的堆栈跟踪,它可以准确地告诉您问题是什么。您正在寻找的工具是调试器,使用断点可以让您在所选时刻检查应用程序的状态

As mentioned before, it's safe to use tempStr.trimm()before parsing to the int.

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