1

i have a function to read user input. it takes a parameter to choose reading Ints or Strings. When i try to make sure that it reads only Ints with while(!sc.hasNextInt()) it works, but only when i step it in debug mode. whenever i try to use it while program is running it throws an exception regardless of input being a number or characters.

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)

this points me to sc.next(); line in my function:

    static String ctecka(int volba)
{
    Scanner sc = new Scanner(System.in);
    String vystup = "vystup";
    if(volba == 1)
    {
        int cislo = 0;
        while(!sc.hasNextInt())
            sc.next();                //this is where exception points

        cislo = sc.nextInt();   
        vystup = Integer.toString(cislo);
    }
    if(volba == 2)
    {
        vystup = sc.nextLine();     
    }
    sc.close();
    return vystup;
}

function is being used from code:

int volba = Integer.parseInt(ctecka(1));     //it returns String so i parse it
somebodyes
  • 11
  • 3

1 Answers1

0

That happens because you close your scanner sc.close(); which closes your inputStream then you try to access it again (have a look here), so to solve your problem, generalize your scanner variable, and then close it only when you finish all the ctecka() method calls, like the following:

Scanner sc;
private void some_method(){
    int volba1 = Integer.parseInt(ctecka(1));
    int volba2 = Integer.parseInt(ctecka(1));
    int volba3 = Integer.parseInt(ctecka(2));
    int volba4 = Integer.parseInt(ctecka(3));
    sc.close();
}

String ctecka(int volba){
    sc = new Scanner(System.in);
    String vystup = "vystup";
    if(volba == 1)
    {
        int cislo = 0;
        while(!sc.hasNextInt())
            sc.next();

        cislo = sc.nextInt();   
        vystup = Integer.toString(cislo);
    }
    if(volba == 2)
    {
        vystup = sc.nextLine();     
    }
    return vystup;
}
Community
  • 1
  • 1
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118