0

这是我得到的,看看你能找到什么。eclipse 说一切都很好,但是当我运行它时,我输入了 5 个数字,然后它询问两行关于最高到最低的问题,反之亦然,然后在我输入答案之前崩溃。我不知所措.

这些是我看到的错误者。在 monty.intarray.main(intarray.爪哇: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;

    }
}
4

1 回答 1

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 对象并根据需要接受尽可能多的输入,最后关闭 Scanner。

希望这可以帮助。

于 2013-10-22T10:25:59.900 回答