程序崩溃了一半,不明白为什么

时间:2013-10-22 09:55:09

标签: java exception crash

继续我所得到的,看看你能找到什么。 eclipse说一切都很好,但是当我运行它时,我会输入5个数字,然后它要求两条线从最高到最低,反之亦然,然后崩溃才能将我的答案输入。我不知所措

这些是我看到的错误。线程“main”java.util.NoSuchElementException中的异常     在java.util.Scanner.throwFor(Scanner.java:907)     在java.util.Scanner.next(Scanner.java:1416)     在monty.intarray.main(intarray.java:25)

import java.util.Arrays;
import java.util.Scanner;


public class intarray {

public static void main(String[] args) {
    System.out.println("Enter a number other than zero, then hit enter. Do this five times.");

    Scanner input1 = new Scanner(System.in);

    int[] array=new int[5];



       for (int whatever = 0; whatever < array.length;whatever++)

            array[whatever]=input1.nextInt();
            input1.close();
       System.out.println("Now tell me if you want to see those numbers sorted from lowest to highest, or highest to lowest.");
       System.out.println("Use the command 'lowest' without the single quotes or 'highest'.");

       Scanner input2 = new Scanner (System.in);
       String answer = input2.next();
       input2.close();

       boolean finish;
       finish = loworhigh(answer);

       if (finish) {
           Arrays.sort(array);
           for (int a = array.length - 1; a >= 0; a--) {
               System.out.print(array[a] + " ");
           }
       }
       else {
           Arrays.sort(array);
           for (int b=0; b<=array.length; b++) {
               System.out.print(array[b] + " ");
           }
       }



       System.out.print(array[0] + ", ");
       System.out.print(array[1] + ", ");
       System.out.print(array[2] + ", ");
       System.out.print(array[3] + ", ");
       System.out.print(array[4] + ".");


  }

public static boolean loworhigh(String ans) {

    if (ans.equalsIgnoreCase("lowest")) return false;
    else  return true;

    }
}

1 个答案:

答案 0 :(得分:2)

当您为input1.close调用时,它还会关闭System.In输入流以及扫描程序。

要检查扫描仪是否仍然可用,您可以尝试:

System.out.println(System.in.available());

并且没有办法重新打开System.In

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

因此它会抛出NoSuchElementException

为避免这种情况,请不要关闭input1,而是使用相同的Scanner对象并接受所需数量的输入,最后关闭扫描器。

希望这有帮助。