The Huxley: java.util.NoSuchElementException: No line found

441 Views Asked by At

I am having a problems when submiting my answer on https://www.thehuxley.com. When I run my code on Eclipse, everything goes OK, but on Huxley, I get this:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at HuxleyCode.main(HuxleyCode.java:12)

And here is the code itself:

import java.io.*;
import java.util.*;

public class HuxleyCode {
  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int menor = 0, pos = 0, entradas = 0, temp;

    entradas = in.nextInt();// WATCH OUT THIS LINE
    in = new Scanner(System.in);

    String valores = in.nextLine();

    entradas = 0;
    for (String val : valores.split(" ")) {
        temp = Integer.valueOf(val);

        if (entradas == 0) {
            menor = temp;
        } else if (temp < menor) {
            menor = temp;
            pos = entradas;
        }
        entradas++;
    }

    in.close();
    System.out.println("Menor valor: " + menor);
    System.out.println("Posicao: " + pos);
  }
}

Just to complement, in the line that i commented "WATCH OUT THIS LINE", if I remove that line, Scanner ignored nextInt() e jumps to NextLine(), causing this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.valueOf(Integer.java:766)
at HuxleyCode.main(HuxleyCode.java:16)

Where is my mistake, why does not work on Huxley?

The expected input is:

10
1 2 3 4 -5 6 7 8 9 10

And output:

Menor valor: -5
Posicao: 4
1

There are 1 best solutions below

0
On BEST ANSWER
entradas = in.nextInt();
String valores ="";
while(in.hasNextLine())
    valores = in.nextLine();

Issue is that nextInt() does not set the position of the Scanner to beginning of next line, thus the first call will return the empty string. This is explained clearly here...
Can't use Scanner.nextInt() and Scanner.nextLine() together

One thing to note is that it works for you because, you reinitialzed the Scanner thus forcing it start from beginning of next line. But unfortunately this would not work with Huxley as they send input programmatically all at once and all lost by losing reference to the first Scanner.

Also the below should work

entradas = in.nextInt();
String valores = in.nextLine();//Get empty Str & Set pos of Scanner to beginning of next line
valores = in.nextLine();