When I use Scanner in Java second Times, object of Scanner sc2 don't convert to integer in this string "int typeOfSort = sc2.nextInt();
".
Eclipse don't show error before start program, but after start show this error. Program can run but when come to string where sc2 must convert to int, programm show error. How fix it?
"
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Buble.main(Buble.java:39)
"
Java Code
import java.util.Scanner;
public class Buble {
public static void main(String[] args) {
int size; // size of Array
int array[]; // Array
System.out.print("Enter size of arrays: ");
// Scanner is tool for input text to console
Scanner sc = new Scanner(System.in);
size = sc.nextInt();
array = new int [size];
sc.close();
for(int i = 0; i < array.length; i++){
double randnum = Math.floor(Math.random() * 1000);
array[i] = (int) randnum;
System.out.println("Element " + i + " = " + (int) randnum);
}
for(int b = 0; b < array.length; b++){
for(int i = 1; i < array.length; i++) {
if(array[i] < array[i-1]){
int a = array[i];
array[i] = array[i-1];
array[i-1] = a;
}
}
}
System.out.println("If you want to sort from smallest to largest
press 1 or 2 if Conversely: ");
Scanner sc2 = new Scanner(System.in);
int typeOfSort = sc2.nextInt(); // String with error
sc2.close();
if(typeOfSort == 1){
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
}
else{
for(int i = array.length; i < array.length; i++){
System.out.println(array[i]);
}
}
}
}