0

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]);
        }
    }
        }
     }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Bogdan
  • 99
  • 1
  • 10

1 Answers1

-1

you are using multiple scanners and you are doing sc.close(); on one of those objects.. that is the reason of the exception

remember: when you close one of the scanners, this is closing under the hood the inputstream (which is shared for all other scanners) too after that, trying to read anything from the remaining scanner instances will throw an exception

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97