Scanner Skipping Over my Opportunity to Input

while this may be entirely trivial my lack of experience has rendered me stumped due to this: with this line of code

String a = scanner.nextLine();

I am shown the following error

 java.util.NoSuchElementException: No line found

I was under the impression that when operations involving the use of Scanner data follow the use of a scanner it will wait for input. This scanner simply leaves me with no chance to enter my input leaving me with operations attempting to use data that does not exist.

Here is the complete relevant code. Forget its inefficiency.

System.out.println(FactBank_QA.qA[ourRANDOM]);
        Scanner scanner = new Scanner (System.in);
        if (scanner.hasNext()){
            String a = scanner.next();
            char b = (char)a.charAt(0);
            if (b == '*') System.exit(0);
        }
        System.out.println(FactBank_QA.qA[ourRANDOM+1]);
        char c; String f = "0";
        do{
            if (scanner.hasNext()){
                f= scanner.next();
            }
                c = (char)f.charAt(0);
        }while(c != 1 || c != 2);
        if (c == 1) {           
        FactBank_QA.qA[ourRANDOM] = ""; 
        FactBank_QA.qA[ourRANDOM+1] = "";
        }

The exception is coming from the first, the second isn’t reached Thanks for the tip too. -Updated the code and removed a .close I no longer receive errors (!) however the second Scanner and subsequent ‘if’ are now non-functional. I did have one .close() but have removed it, this fixed the first use of ‘scanner’

Answer

Firstly, be cautious of where you call close(). This is a good reference.

You also seem to have a logic error here:

do{
    if (scanner.hasNext()){
        f= scanner.next();
    }
        c = (char)f.charAt(0);
}while(c != 1 || c != 2);

c is a char. Remember that '0' is very different than 0. You may instead want: while(c != '1' || c != '2');. You might need to update other areas of your code as well.

Another logic error, what if I press enter without typing anything? (psst: f.charAt(0))

One more: while(c != '1' || c != '2') is an infinite loop, since c can never be simultaneously equal to ‘1’ and ‘2’.

Leave a Reply

Your email address will not be published. Required fields are marked *