我一直在制作一个简单的java程序作为学校的家庭作业。当我添加一个从.txt文件中检索2D数组的方法时,出现了这个错误。编译时程序不显示任何错误。我是一名新程序员,所以请仔细检查添加或更改的内容。除了手头的问题,请随时给我进一步的提示和建议。
提前致谢
以下是代码:
import java.util.*;
import java.io.*;
public class simpleAI2
{
public static void main (String [] args)
{
int count = 0;
String[][] array = new String [20][4];
simpleAI2.getArrayData(array);
String leaveQ;
int rep = 1;
do
{
int countTwo = 0;
boolean flag = false;
Scanner scanName = new Scanner (System.in);
Scanner scanSport = new Scanner (System.in);
Scanner leave = new Scanner (System.in);
System.out.println("My name is A.I.S.C.M.B.T. What is your name?");
array[count][1] = scanName.nextLine ();
System.out.println("Hi "+array[count][1]+"! What's your favourite sport?");
array[count][2] = scanSport.nextLine ();
String sport = array[count][2];
for(int x = 1;x<rep;x++)
{
if(!array[countTwo][2].equals(null) && array[countTwo][2].equals(array[count][2]))
{
flag = true;
x = 28;
}
else
{
flag = false;
}
countTwo ++;
}
countTwo --;
if(flag == true)
{
System.out.println("I know "+array[countTwo][2]+". It is "+array[countTwo][3]+". My friend "+array[countTwo][1]+" knows it");
}
if(flag == false)
{
System.out.println("I don't know "+array[count][2]+". I only know robot boxing. Robots hit each other until one malfunctions. What is this alien sport you speak of?");
array[count][3] = scanSport.nextLine ();
}
System.out.println("Go again? Type no to leave me :(");
leaveQ = leave.nextLine ();
rep ++;
count ++;
if(leaveQ.equals("no"));
{
simpleAI2.Save(array);
}
}while (!leaveQ.equals("no"));
}
public static void Save(String [][] array){
try {
PrintWriter writer = new PrintWriter(new File("arrayData.txt"));
for(int x=0; x<array.length; x++){
for(int y=0; y<array[x].length; y++){
writer.write(String.valueOf(array[x][y]));
}
writer.println();
}
writer.flush();
writer.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void getArrayData(String [][] array){
try {
Scanner scan2 = new Scanner(new File("arrayData.txt"));
for(int i=0; i<array.length; i++){
for(int j=0; j<array[i].length; j++)
{
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
如果您在没有任何内容可供阅读时致电Scanner
函数next(),则会抛出NoSuchElementException
。
将您的代码更改为以下内容:
public static void getArrayData(String [][] array)
{
try
{
Scanner scan2 = new Scanner(new File("arrayData.txt"));
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[i].length; j++)
{
if ( ! scan2.hasNext() ) //if there's nothing left to read
return; //exit the function
array[i][j]=scan2.next();
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}