空数组时显示错误

时间:2015-12-03 15:55:58

标签: java arrays

我在java中创建了一个接受文件输入的反向抛光符号计算器。其中一个要求是从计算中也生成某些统计数据。 下面是我的代码的两个片段。

static void fileInput() throws IOException
{
    input = new Scanner(System.in);
    try
    {
    String currentLine = new String();
    int answer = 0;
    //Open the file
    display("Enter File Name: "); 
    FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
    String strLine; // create string vars
    //loop to read the file line by line
    while ((strLine = br.readLine()) != null)   { // Whilst the buffered readers read line method is not null, read and validate it.
        currentLine = strLine; 
        if(strLine.trim().isEmpty())
        { 
            display("You have entered a blank line, the program will now exit");
            System.exit(0); 
            }
    if(isValidLine(currentLine)) 
    { 
        validList.add(currentLine); 
        validlines++;
        String[] filearray = new String[3];
        filearray = currentLine.split(" ");             
    int val1 = Integer.parseInt(filearray[0]);
    int val2 = Integer.parseInt(filearray[1]);
        display("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
    switch(filearray[2]) { 
    case("+"):
            answer = val1 + val2;
            stats.add(answer);
        break;
    case("-"):
            answer = val1 - val2; 
            stats.add(answer);
        break; 
    case("/"):
            answer = val1 / val2;
            stats.add(answer);
        break;
    case("*"):
            answer = val1 * val2;
            stats.add(answer);
        break;
        }
        display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
    }
    }
    }
    catch (FileNotFoundException e) 
{
        display("Please Enter a valid file name");
}
        display("Evaluations Complete");
        display("=====================");
        display("Highest Result: " + Collections.max(stats));
        display("Lowest Result: " + Collections.min(stats));
        display("Aggregate Result: " + sum(stats));
        display("Average Result: " + sum(stats) / validlines);
        display("Total Valid Lines: " + validlines); 
        display("Total Invalid Lines: " + invalidlines);
}   

这是我的数组列表的代码。

Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.Collections.max(Unknown Source)
at Assignment.fileInput(Assignment.java:156)
at Assignment.main(Assignment.java:177)

我需要它,以便如果文本文件中没有有效的计算结果,则最高,最低和平均结果显示为' n / a'相反,它们会在我的控制台中显示java错误。

{{1}}

1 个答案:

答案 0 :(得分:4)

替换

Collections.max(stats)

(!stats.isEmpty() ? Collections.max(stats) : "n/a")

(类似于Collections.min

您还希望处理validlines == 0的情况,以避免/ validlines中的除零错误。