Ayoub_Prog
Ayoub_Prog

Reputation: 316

NoSuchElementException : No line found

I am working on a simple project, I took it from a website that gives some challenge to improve my coding skill in java.

import java.util.Scanner;

public class Test1 {        
  public void test() {
    Scanner in = new Scanner(System.in);
    System.out.println("enter something :");
    String str = in.nextLine();
    StringBuilder sb = new StringBuilder(str);
    if (str.isEmpty()) {
        System.out.println("you should write something");
    }
    if(str.length()<=30){
        System.out.println("reverse : "+sb.reverse());
    }else {
        System.out.println("Error");
    }
    System.out.println("----------------------");   
  }

  public static void main(String[] args) {  
    Test1 c = new Test1 ();
    for (int i = 1; i <= 10 ; i++) {
        System.out.println("case number : " +i);
        c.test();
    }
  }
}

case number : 1
enter something : ayoub
reverse : buoya
----------------------
...loop continue ..

My code works like I want in terminal of eclipse, but when I put it into the "code editor" of the web site, this last one gives me a runtime error that says:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1540)
at Test1.test(Test1.java:10)
at Test1.main(Test1.java:31)

I tried to search on StackOverflow for some solutions but I didn't find it.

Upvotes: 4

Views: 5315

Answers (1)

Rann Lifshitz
Rann Lifshitz

Reputation: 4090

You are probably using an online java code editor/compiler which does not have an stdin input.

As stated by arcy, you are probably using an IDE with a built-in console window which allows you to pass standard inputs to your program.

The following online editor will allow you to add inputs. You should take care of the way you are using the nextLine method of Scanner:

The exception you are getting is the result of the scanner not getting any inputs, as can be seen here. I suggest you refactor your loop on the scanner using the method hasNextLine of Scanner.

Upvotes: 2

Related Questions