user5153746
user5153746

Reputation:

Getting input inside a loop using Java

I'm trying to use scanner.nextLine() inside a loop, but I get an exception. The problem is located in this part of the code.

        while(!sentence.equals("quit")){
        dealWithSentence(sentence, voc);
        System.out.println("Enter your sentence:");
        sentence = scanner.nextLine();
    }

There is the exception:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at il.ac.tau.cs.sw1.ex4.SpellingCorrector.main(SpellingCorrector.java:34)

That's my full method code:

    public static void main(String[] args) throws Exception{
    Scanner scanner = new Scanner(System.in);
    String filePath = scanner.nextLine();
    if (filePath.contains(" ")){
        scanner.close();
        throw new Exception("[ERROR] the file path isnt correct");
    }

    File file = new File(filePath);
    String[] voc = scanVocabulary(new Scanner(file));
    if (voc == null)
    {
        scanner.close();
        throw new Exception("[ERROR] the file isnt working");

    }


    System.out.println("Read " + voc.length + " words from " + file.getName());

    System.out.println("Enter your sentence:");

    String sentence = scanner.nextLine();

    while(!sentence.equals("quit")){
        dealWithSentence(sentence, voc);
        System.out.println("Enter your sentence:");
        sentence = scanner.nextLine();
    }
    scanner.close();

Upvotes: 1

Views: 1363

Answers (2)

user1438038
user1438038

Reputation: 6059

Check scanner.hasNextLine() before you use scanner.nextLine():

if (scanner.hasNextLine()) {
  sentence = scanner.nextLine();
}

Otherwise, the scanner might not have any element and cannot provide a next line.

Usually, you will read your input in a loop, such as:

while (scanner.hasNextLine()) {
  System.out.println("Line: " + scanner.nextLine());
}

Upvotes: 2

Kulvinder Singh
Kulvinder Singh

Reputation: 307

Scanner.nextLine() works as follows..

   String s = "Hello World! \n 3 + 3.0 = 6.0 true ";

   // create a new scanner with the specified String Object
   Scanner scanner = new Scanner(s);

   // print the next line
   System.out.println("" + scanner.nextLine());

   // print the next line again
   System.out.println("" + scanner.nextLine());

   // close the scanner
   scanner.close();
   }

this will give you the following output

Hello World!
3 + 3.0 = 6.0 true 

So basically it starts scanning and skips until the first new line character, and then it returns whatever it has skipped so far as the output. In your case if you have only a single sentence and no new line (\n) in it at all, it will skip the entire length and never find a new line. thereby throwing the exception... add a new line character in mid of sentence and see if the exception goes away

Credits go to : http://www.tutorialspoint.com/java/util/scanner_nextline.htm

Upvotes: 4

Related Questions