Reputation: 47
heres what i got, take a look and see what you can find. eclipse says everything is good to go, but when i run it, i get to input the 5 numbers, then it asks the two lines about highest to lowest or vice versa, then crash before i can put my answer in. im at a loss.
these are the errorrs i see. Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1416) at 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;
}
}
Upvotes: 0
Views: 90
Reputation: 737
When you call on for input1.close, it also closes System.In input stream along with the scanner.
To check if Scanner is still available you can try:
System.out.println(System.in.available());
And there is no way to re-open 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.**
And thus it throws NoSuchElementException
To avoid this, don't close input1 and instead use the same Scanner object and accept as many inputs as required and finally close the Scanner.
Hope this helps.
Upvotes: 2