Exception in thread "main" java.util.Nosuchelementexception: No line found

Asked

Viewed 769 times

1

I am new in programming and the problem asks to store in vector the name of 10 products. Then the program must request the range of products that must be displayed (for example: 3 to 7).

The error says:

"Exception in thread "main" java.util.Nosuchelementexception: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651) Exercicio5.main(Exercicio5.java:21)"


package aula2;
import java.util.Scanner;

public class Exercicio5 {

    public static void main(String[] args) {

        String [] produto = new String[10];

        for (int i=1; i<=10; i++) {

            Scanner p = new Scanner(System.in);
            System.out.println("Insira o " + (i)+ "° produto de 10:");
            produto[i] = p.nextLine();
            p.close();
        }

        Scanner f = new Scanner(System.in);

        System.out.println("Insira a faixa mínima:");
        int minimo = f.nextInt();

        System.out.println("Insira a faixa máxima:");
        int maximo = f.nextInt();

        for (int i=minimo; i<maximo+1; i++) {
            System.out.println(produto[i-1]);
        }
        f.close();
    }

}

1 answer

1



import java.util.Scanner;

public class Exercicio5 {

    public static void main(String[] args) {

        String [] produto = new String[10];

        Scanner p = new Scanner(System.in);

        for (int i=0; i<10; i++) {


            System.out.println("Insira o " + (i+1)+ "° produto de 10:");
            produto[i] = p.nextLine();

        }

        System.out.println("Insira a faixa mínima:");
        int minimo = p.nextInt();

        System.out.println("Insira a faixa máxima:");
        int maximo = p.nextInt();

        for (int i=minimo-1; i<=maximo-1; i++) {
            System.out.println(produto[i]);
        }

        p.close();
    }
}

P.S. I advise to test the user input for the minimum and maximum variables, to ensure that they are between 0 and 10 and that minimum <= maximum.

  • 1

    Can you give more details? In English?

  • The Scanner object is declared and released outside the first cycle. The logic for traversing the array with index i was not correct. You should, just my suggestion, test the maximum and minimum limits entered by the user and even if min is less than max.

  • 2

    You can edit the answer?

  • Maniero, I’m new to this, I’m trying to understand, I’m already editing

  • 1

    Filipe, we are at [pt.so] and all questions and answers must be in Portuguese. Could [Dit] his reply translate it and also include the explanation of his last comment? Thus it is complete (future visitors will not need to "hunt" information in the comments) and also in the correct language

Browser other questions tagged

You are not signed in. Login or sign up in order to post.