Java parseInteger 抛出错误

Java parseInteger throwing error

我的测试人员有以下代码片段 class。

     FileReader freader=new FileReader(filename);
     BufferedReader inputFile=new BufferedReader(freader);
     int numScores = 0;
     String playerType = "";
     String nameHome = "";
     String playerName = "";
     String home = "";
     String location = "";
     int score = 0;
     String date = "";
     double courseRating = 0;
     int courseSlope = 0;

     ArrayList<Player> players = new ArrayList<Player>();

     while (inputFile.read()!= -1) {
        numScores = Integer.parseInt(inputFile.readLine()); 
        playerType = inputFile.readLine();
        nameHome = inputFile.readLine();
        StringTokenizer st = new StringTokenizer(nameHome,",");
        playerName = st.nextToken();
        home = st.nextToken();

程序编译,但是当测试器是 运行 时,我得到以下输出错误。

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at PlayerTest.main(PlayerTest.java:34)

我已经尝试对此进行研究,但我犯规的是,当它更改从数据文件读取的字符串并将其转换为 int 时,可能存在 space。我试着直接读入一个字符串,修剪字符串,然后转换为 int,但它得到了同样的错误。

这是替换 numScores = Integer.parseInt(inputFile.readLine());

的代码
        tempScores = inputFile.readLine();
           tempScores.trim();
           System.out.println(tempScores);
           numScores = Integer.parseInt(tempScores);

感谢任何帮助。

*编辑以显示示例数据 来自文件的示例数据

3
B
James Smith, Strikers
FWB Bowling, 112,09/22/2012
White Sands, 142,09/24/2012
Cordova Lanes,203,09/24/2012

您可以将其全部放在 if 语句中:

if(!tempScores.equalsIgnoreCase(""))
{

可能,您的文件包含空行。这些被读作“”,因此不能转换为 int。

另外,有可能你通过while循环头中的read-statement读取了每行的第一个字符,从而在rea​​dline命令中被忽略。那么长度为1的数字(比如“1”)就会变成空行。

无论如何,你的循环构造是一个错误。

你需要了解this请看一下

基本理解是

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught.
} 

还有一个finally块,即使出现错误也会一直执行。它是这样使用的

try { 
   //Something that can throw an exception.
} catch (Exception e) {
  // To do whatever when the exception is caught & the returned.
} finally {
  // This will always execute if there is an exception or no exception.
}

在您的特定情况下,您可以有以下例外情况 (link)。

InputMismatchException - 如果下一个标记与整数正则表达式不匹配,或者超出范围 NoSuchElementException - 如果输入已用完 IllegalStateException - 如果此扫描器已关闭

所以你需要捕获像

这样的异常
try { 
   rows=scan.nextInt();
} catch (InputMismatchException e) {
  // When the InputMismatchException is caught.
  System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
  // When the NoSuchElementException is caught.
  System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
  // When the IllegalStateException is caught.
  System.out.println("Scanner is close");
} 

我 运行 今天遇到了类似的问题。我正在阅读来自 REST 端点的响应并尝试解析 json 响应。砰!遇到错误。后来我意识到该文件有一个 BOM。

我的建议是创建一个变量

String var = inputFile.readLine();
int numScores = Integer.parseInt(var);

添加一个断点并检查 var 包含的内容,在我的例子中,响应有一个 BOM 和一个空的 unicode 字符代码 65279 / 0xfeff。在任何物有所值的调试器中,您都应该能够看到每个字符。

如果是这种情况,您需要从字符串中删除该值。

我使用这个库来检测这个问题org.yaml:snakeyaml:1.16

import org.yaml.snakeyaml.reader.UnicodeReader;

//more code

  private String readStream(InputStream inputStream) throws IOException {
    UnicodeReader unicodeReader = new UnicodeReader(inputStream);
    char[] charBuffer = new char[BUFFER_SIZE];
    int read;
    StringBuilder buffer = new StringBuilder(BUFFER_SIZE);
    while ((read = unicodeReader.read(charBuffer,0,BUFFER_SIZE)) != -1) {
      buffer.append(charBuffer, 0, read);
    }
    return buffer.toString();
  }