2014-01-23 134 views
0

我在阅读和存储文本文件中的整数时遇到问题。我正在使用一个int数组,所以我想在没有列表的情况下执行此操作。我收到一个输入不匹配异常,我不知道该如何解决这个问题。正在读取的文本文件也包含字符串。从txt文件读取整数并存储到数组中

public static Integer[] readFileReturnIntegers(String filename) { 
    Integer[] array = new Integer[1000]; 
    int i = 0; 
    //connect to the file 
    File file = new File(filename); 
    Scanner inputFile = null; 
    try { 
     inputFile = new Scanner(file); 
    } 
    //If file not found-error message 
     catch (FileNotFoundException Exception) { 
      System.out.println("File not found!"); 
     } 
    //if connected, read file 
    if(inputFile != null){   
     System.out.print("number of integers in file \"" 
       + filename + "\" = \n"); 
     //loop through file for integers and store in array  
     while (inputFile.hasNext()) { 
      array[i] = inputFile.nextInt(); 
      i++; 
     } 
     inputFile.close(); 
    } 
    return array; 
    } 
+1

发表您的文本文件的内容... – gowtham

+0

检查'next()'[isNumeric](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNumeric%28java.lang.CharSequence %29) –

+0

'hasNextInt()'when using nextInt()'.. – 2014-01-23 06:06:12

回答

2

你可能会使用类似的东西(跳过任何非int),你应该关闭你的Scanner

// if connected, read file 
if (inputFile != null) { 
    System.out.print("number of integers in file \"" 
     + filename + "\" = \n"); 
    // loop through file for integers and store in array 
    try { 
    while (inputFile.hasNext()) { 
     if (inputFile.hasNextInt()) { 
     array[i] = inputFile.nextInt(); 
     i++; 
     } else { 
     inputFile.next(); 
     } 
    } 
    } finally { 
    inputFile.close(); 
    } 
    // I think you wanted to print it. 
    System.out.println(i); 
    for (int v = 0; v < i; v++) { 
    System.out.printf("array[%d] = %d\n", v, array[v]); 
    } 
} 
+0

Wooh似乎已经做到了!如果我打印出每个整数,我是否要使用for循环? –

+0

@ Asiax3我编辑了这55分钟前...看看'printf'这一行。 –

+0

哦,谢谢你的Elliott!但不幸的是,我在做我的程序全错了:(我需要通过hasNextLine()方法遍历文件,使用try和catch来确定哪些词是整数,哪些不是使用InputMismatchException。提交另一个问题,因为我问这个不正确的帮助:(。 –

2

变化hasNext()hasNextInt()在while循环。

+0

我试过这个,当试图打印出其中一个整数时,我得到了空值。 –

+0

@ Asiax3要循环遍历非整数,您需要将其包装在另一个hasNext()while循环中,并在hasNextInt()while循环下使用next()。这与艾略特所说的实际上是一样的。 – Didericis

0

你需要做的就是你得到一个新的价值,并试图把它变成你需要检查,以确保它实际上是一个int数组之前,如果没有则跳过它并转到下一个值。或者,您可以创建所有值的字符串数组,然后仅将整数复制到单独的数组中。但是,第一种解决方案可能是两者中较好的一种。

而且......正如在它往往是更容易为字符串读取整数,然后从中解析值的评论提到...

相关问题