lucas
lucas

Reputation: 29

while loop error in Java

well im currently learning java my myself but from what i know i just cant seem to fix this problem currently testing a script where if u dont type ur name exactly u must re-type it but this error appears i searched everywhere but most of the things i tried dont work

Please type in your name: 
lucas
Welcome lucas
Confirm your name:
luca
Please type in your name: 
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at input.main(input.java:9)

here is the code:

import java.util.Scanner;

public class input {
    public static void main(String[] args) {

        while (true) {
            try (Scanner input = new Scanner(System.in)) {
                System.out.println("Please type in your name: ");
                String name = input.nextLine();
                System.out.println("Welcome " + name);
                if (name.equals("nico")) {
                    System.out.println("bitch");
                    break;
                } else {
                    System.out.println("Confirm your name:");
                    String name1 = input.nextLine();
                    if (name1.equals("nico")) {
                        System.out.println("Hello " + name1 + "... bitch");
                    } else if (name1.equals(name)) {
                        System.out.println("Thank you");
                        break;
                    }
                }
            }
        }
    }
}

Upvotes: 1

Views: 329

Answers (2)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

Don't put the Scanner into your loop.

Loop while the scanner still has input.

Currently, you create new Scanner too often.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

Move the try-with-resources to around your while loop. When execution leaves the try-with-resources, Java closes the resources. Here, that resource is the standard input, which cannot be re-opened.

try (Scanner input = new Scanner(System.in)) {
    while (true) {
        System.out.println("Please type in your name: ");

You actually don't really need the try-with-resources here. Don't close standard input/output/error.

Upvotes: 2

Related Questions