Home > Back-end >  how to fix : Exception in thread "main" java.util.NoSuchElementException: No line found
how to fix : Exception in thread "main" java.util.NoSuchElementException: No line found

Time:04-14

I try input my name into scanner but it throws an exception:

Username is: danny

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at NonDuplicateCharacters.main(NonDuplicateCharacters.java:10)

my input

danny
1 2 3 4 3 2 1

expected output

danny
4

my code:

import java.util.*;  
public class NonDuplicateCharacters {  
     public static void main(String[] args) {  
     Scanner myObj = new Scanner(System.in);
     String userName = myObj.nextLine(); 
     System.out.print("Username is: "   userName);
    
    
        Scanner input1= new Scanner(System.in);
        String number = input1.nextLine();
        int count;  
          
        
        char string[] = number.toCharArray();  
          
        
        for(int i = 0; i <string.length; i  ) {  
            count = 1;  
            for(int j = i 1; j <string.length; j  ) {  
                if(string[i] == string[j] && string[i] != ' ') {  
                    count  ;  
                    string[j] = '0';  
                }  
            }  
           
            if(count == 1 && string[i] != '0' && string[i] != ' ')  
                System.out.println(string[i]);  
        }  
    }  
}  

i read solution to change nextline() next(), i try but it doesnt work. sorry for bad grammar

CodePudding user response:

You're creating two Scanner objects based on System.in.

Each Scanner will read from System.in and consume some of its input. That means that the first one might have already read some things into its buffer when you created the second one.

The short answer is: never create multiple Scanner objects based on the same parameter, simply continue using the existing scanner. For example this would fix your issue:

public static void main(String[] args) {  
     Scanner myScanner = new Scanner(System.in);
     String userName = myScanner.nextLine(); 
     System.out.print("Username is: "   userName);
    
    
     String number = myScanner.nextLine();
     // ... rest of your code ...

CodePudding user response:

Change

System.out.print("Username is: "   userName);

to this:

System.out.println("Username is: "   userName);

And you are good to go.

The input/output:

danny
Username is: danny
1234321
4

EDIT

Even if you change nothing in your code, it works absolutely fine.

danny
Username is: danny1234321
4

Which makes conclusion simple. Don't use that online compiler.

  • Related