对于我的程序,我要使用数组从数据文件中分离正数和负数。我能够编译程序,但是当我运行主程序时,出现错误java.util.nosuchelementexception。我不太确定错误发生在哪里以及为什么会收到它。非常感谢您的帮助。
这是程序
import java.util.Scanner;
import java.io.*;
public class Prog404aAP
{
public static void main(String args[])
{
//declares variables and arrays;
int[] pos = new int [13];
int[] neg = new int [13];
int newFile;
//sets up kbrader
Scanner kbReader=new Scanner(System.in);
//sets up scanner
Scanner inFile = null;
//input for 1st set of data
try
{
inFile = new Scanner(new File("prog404a1.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(0);
}
System.out.println("Run File? 1 for yes 2 for no. Only 2 files are available to run");
int decision = kbReader.nextInt();
while( decision == 1 )
{
//header
System.out.println("Positive \t Negative");
//stores the numbers from the file into both arrays depending on value
for(int index = 0; index < 13; index++)
{
if(inFile.nextInt() < 0)
{
pos[index] = inFile.nextInt();
}
else
{
neg[index] = inFile.nextInt();
}
}
//for loop for formatted output
for(int index = 0; index < 13; index++)
{
System.out.println( pos[index] +"\t " +neg[index]);
}
System.out.println("Run File? 1 for yes 2 for no. Only 2 files are available to run");
newFile = kbReader.nextInt();
if(newFile == 1)
{
decision = 1;
//sets up scanner
inFile = null;
//input for 2nd set of data
try
{
inFile = new Scanner(new File("prog404a2.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
System.exit(0);
}
}
else
{
decision = 2;
}
}
}
}
这是我的数据文件prog404a1
3
66
54
-8
22
-16
-56
19
21
34
-34
-22
-55
-3
-55
-76
64
55
9
39
54
33
-45
这是我的prog404a2数据文件
51
-66
-54
-22
-19
8
10
56
34
22
55
3
55
76
45
-21
-34
-64
-55
-9
-89
-54
-3
32
45
-25
堆栈跟踪
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Prog404aAP.main(Prog404aAP.java:56)
最佳答案
for(int index = 0; index < 13; index++)
{
if(inFile.nextInt() < 0)
{
pos[index] = inFile.nextInt();
}
else
{
neg[index] = inFile.nextInt();
}
}
您为每个值两次调用
nextInt()
。当到达第7个元素时,您实际上是在尝试读取不存在的第14个元素,并导致此异常。您需要将值放入变量中:for(int index = 0; index < 13; index++)
{
int nextVal = inFile.nextInt();
if(nextVal < 0)
{
pos[index] = nextVal ;
}
else
{
neg[index] = nextVal ;
}
}