【问题标题】:program crashes halfway through, no idea why程序中途崩溃,不知道为什么
【发布时间】:2013-10-22 09:55:08
【问题描述】:

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

这些是我看到的错误者。线程“主”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;

    }
}

【问题讨论】:

  • 一个猜测,但对于 (int b=0; b

标签: java exception crash


【解决方案1】:

当您调用 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。

希望这会有所帮助。

【讨论】:

  • 帮助很大。它现在可以工作了,我从最低到最高正确地得到了我的输出,但是即使程序运行正确,我最后也会得到这个错误。线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 5 at monty.intarray.main(intarray.java:41)
  • 好的,我修好了,忽略,问题解决了,非常感谢扫描仪的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多