【发布时间】:2013-11-29 21:14:47
【问题描述】:
我创建了一个名为fileWriter 的方法,它将一个随机整数数组输出到一个txt 文件中。这可以正常工作,但是当我尝试使用我的其他方法 fileReader 应该读取该文件并将其添加到另一个数组时,它会给我一个 NoSuchElementException 即使文件已经创建(我已经检查过)。我第二次运行该程序时,它确实像预期的那样工作,但文件现在的数字是以前的两倍。我曾尝试在将数组导入之前创建一个空白文件,但第一次运行程序时它仍然给我相同的错误消息。如果有人能提示为什么会发生这种情况,将不胜感激。
这是我的代码:
/*******************************************************************************/
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class randomNum {
public static void main(String[] args) {
FileWriter f;
try {
//here i create a blank file to try and fix the NoSuchElements exception
PrintWriter x=new PrintWriter(f=new FileWriter("C:\\LOG\\a3Unsorted.txt"));
} catch (IOException e) {
e.printStackTrace();
}
Random gen = new Random();
//This creates the original array
int[] array=new int[10];
for(int i=0;i<array.length;i++){
int rdm=gen.nextInt(100);
array[i]= rdm;
}
//call the other class
Sort num = new Sort(array);
//call method fileWrite from class Sort to send the array to the file
Sort.fileWrite(array);
//call method fileRead from class Sort to read the file thats been created (this is where i think could be the issue)
Sort.fileRead(array);
for(int i=0;i<array.length;i++){
System.out.println(array[i]);
}//prints out the array from the file in default output
}
}
/***************************************************************************/
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Sort {
private static PrintWriter out;
private static FileWriter file;
public Sort(int[] array) {
}
/***************************************************************************/
public static void fileRead(int[] array){
Scanner s = null;
try {
s = new Scanner(new File("C:\\LOG\\a3Unsorted.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
array[i] = s.nextInt();
}
/**************************************************************************/
public static void fileWrite(int[]array){
try {
out = new PrintWriter(file = new FileWriter("C:\\LOG\\a3Unsorted.txt",true));
for (int i=0; i<array.length; i++)
{
out.println(array[i]);
}
out.close();
} catch (IOException ex) {
}
}
}//class
【问题讨论】:
-
能否请您发布异常的堆栈跟踪?
-
这是我运行程序时得到的堆栈跟踪:
-
java.util.Scanner 的 java.util.Scanner.next(Unknown Source) 的 java.util.Scanner.throwFor(Unknown Source) 的线程“main”java.util.NoSuchElementException 中的异常。 nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Sort.fileRead(Sort.java:82) at randomNum.main(randomNum.java:30)