Quatsch
Quatsch

Reputation: 392

NoSuchElementException in Scanner when using next()

I am basically trying to fill a String[][]. Whenever I use the next() function of my scanner it throws me an exception.

Can you help, please?

public static void main(String[] args) throws NumberFormatException, Exception {

    int k,i;
    int n = Integer.parseInt(IO.promptAndRead("Bitte geben Sie eine Zahl zwischen 5 und 50 ein: ")); // any number between 5 and 50
    String name= IO.promptAndRead("Bitte geben Sie Ihren Vor- und Zunamen ein: "); //for example "Hans Zimmermann"
    n=n-1;
    String[][] matrix = new String[n][n];

    Scanner sc = new Scanner(name);

    boolean b_switch = false;

    for (i = 0; i<n;i++) {
        b_switch = !b_switch;
        if (b_switch == true) {
            for (k = 0; k<n;k++) {
                matrix[i][k] = sc.next();
            }
            if (i+1 < n){
                matrix[i+1][k] = sc.next();
            }
        }
        else {
            for (k = n; k>0;k--) {
                matrix[i][k] = sc.next();
            }

            if (i+1 < n){
                matrix[i+1][k] = sc.next();
            }
        }
    }

My console output:

Bitte geben Sie eine Zahl zwischen 5 und 50 ein: 15
Bitte geben Sie Ihren Vor- und Zunamen ein: asdf
    Exception in thread "main" java.util.NoSuchElementException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at ep1_uebung6.Maender.main(Maender.java:25)

Upvotes: 0

Views: 56

Answers (2)

Adheep
Adheep

Reputation: 1585

Modify like this, and it should work for you

for (i = 0; i<n;i++) {
  if(sc.hasNext()) {
    b_switch = !b_switch;
    if (b_switch == true) {
        for (k = 0; k<n;k++) {
            matrix[i][k] = sc.next();
        }
        if (i+1 < n){
            matrix[i+1][k] = sc.next();
        }
    }
    else {
        for (k = n; k>0;k--) {
            matrix[i][k] = sc.next();
        }

        if (i+1 < n){
            matrix[i+1][k] = sc.next();
        }
    }
 } else {
    break;
 }
}

Hope this helps!

Upvotes: 0

dReAmEr
dReAmEr

Reputation: 7196

You are getting NoSuchElementException, because you are using sc.next() in your code without verifying whether there is any element or not.

You should make a check for existence before calling sc.next(), like below.

if (sc.hasNext()) {
    matrix[i][k] = sc.next();
}

For more information, refer the JavaDoc.

Upvotes: 1

Related Questions