Search code examples
javanosuchelementexception

how to fix : Exception in thread "main" java.util.NoSuchElementException: No line found


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


Solution

  • 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 ...