Error Converting String to Numbers in Java

Asked

Viewed 493 times

0

In my last post (do/while repeats the expression twice) was having an input overlay problem using the Scanner class, and according to the links placed in the answer, we cannot use nextLine() after nextInt().

Now I’m making another algorithm and falling into the same problem. According to the link solution used as a response, I used Integer.parseint() to solve the problem. It turns out that java.lang.Numberformatexception: For input string: ""

From what I understand searching in English is because the String is empty. Ok, it is. But it is because it returns the error even before I can type, and has a row before asking for the input of a value in the String.

inserir a descrição da imagem aqui

As you can see in the image above, after I insert the third note it already gives the error, before I put the frequency.

Follows the code:

public static void main(String[] args) {

    Scanner read = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat("0.00");

    String matricula;
    String resultado;
    String frequencia = "0";
    int freq;
    double nota1, nota2, nota3, notaFinal;
    double maiorNota;
    double menorNota;
    double mediaGeral = 0;
    int totalRep = 0;
    double percentRepFreq;

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

        System.out.print("Entre com a matrícula do aluno " + i + ": ");
        matricula = read.nextLine();

        System.out.print("Digite as 3 notas do aluno " + i + "\nNota 1: ");
        nota1 = read.nextDouble();
        System.out.print("Nota 2: ");
        nota2 = read.nextDouble();
        System.out.print("Nota 3: ");
        nota3 = read.nextDouble();

        System.out.print("Digite a frequência do aluno " + i + ": ");
        frequencia = read.nextLine();

        freq = Integer.parseInt(frequencia);
        if (freq < 40) {
            totalRep += 1;
        }

        notaFinal = (nota1 + nota2 + nota3) / 3;
        mediaGeral += notaFinal;

        if (notaFinal >= 6 && freq >= 40) {
            resultado = "Aprovado.";
        } else {
            resultado = "Reprovado.";
        }

        System.out.println("Aluno " + i + ", com matrícula " + matricula + ", teve frequência de " + frequencia
                + ", nota final: " + notaFinal + " e foi " + resultado);

        System.out.println(" ");
    }

    percentRepFreq = (int) totalRep / 5 * 100;

    System.out.println("Media geral da turma: " + mediaGeral);
    System.out.println("Total de alunos reprovados: " + totalRep);
    System.out.println(percentRepFreq + "% " + "dos alunos foram reprovados por frequência.");

}

}

  • Behold this your question and all those marked as duplicates attentively. The problem is the same. the parseInt that you put it doesn’t change anything because it continues to have nextDouble followed by nextLine

2 answers

1

This happens because nextDouble() (or nextInt(), nextFloat() etc) do not function in the same way as nextLine().

The nextLine() rescues the next line of your input, now nextDouble() rescues the next double of its input, and this need not necessarily be the entire content of the line.

For example: if in creating the Scanner you do:

Scanner read = new Scanner(System.in).useDelimiter(" ");

And in execution, when reporting the first note, instead of passing a single value, pass three values separated by space (e.g.: 1 2 3 (has one last space after the 3)), notes 2 and 3 will be captured automatic precisely because these methods do not read the whole line but only the next Double.


To solve the problem there are basically two options:

  • Call the method nextLine() after each call from nextDouble()

  • Or change from nextDouble() for nextLine() and do the conversions "in hand" (something like Double.parseDouble(val))

  • Now I understand better, I swear I read the other posts, but I thought it was only with int the problem. Thank you so much! But just to be 100% clear then: no matter the order whether comes nextDouble or Line first, is that it? Ps: I want to deepen and understand better, but I marked the answer of the kervincandido because it worked perfectly replacing the two nextLine by the next and it was very practical.

  • @Luisfernando the order matters yes... If you want to use the nextDouble() you will need to call the nextLine() next. Particularly, me I think you’d better just use the nextLine() and ensure the conversion in the code.. Until pq the user can enter 8,5 instead of 8.5 and the code will break, you know?

  • @Luisfernating the answer you marked partially solves your problem. In fact, it hides your problem. It doesn’t solve it or explain why the code behaves that way. As far as I’m concerned, it’s okay not to mark my answer as correct, I just don’t think the one that’s currently marked doesn’t solve your problem... If you follow the logic of the answer you can never use the nextLine(), right?

  • 1

    Right, I really could never, but since this code is simple I had no need to use nextline, solved it. I think it’s one of the possible solutions, at least for simpler codes. Now it may be necessary in another code or situation I have to use nextline and so I deepened the question. But in fact, rereading now, I see that with these answers I learned much more, even had not thought about this question of ",". Now yes I understand. Thanks for the layout.

0


use next(); invez de nextLine() when picking up frequency

frequencia = read.next();

Browser other questions tagged

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