Program that reads real number in Java

Asked

Viewed 1,397 times

0

I’m having a rather idiotic doubt let’s say so, but I’m not remembering what I have to do to make it right. I must create a program that reads an entire number and prints on the screen.

Here’s what I got:

import java.io.IOException;
import java.util.Scanner;

public class Real {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        double real;

        Scanner le = new Scanner(System.in);

        System.out.println("Digite um numero real");
        real = le.nextDouble();

        System.out.println("O numero digitado é:" +real);

        le.close();


    }

}

I can type the number (type for example 2.35) but the following error:

Digite um numero real
3.2
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextDouble(Unknown Source)
    at Real.main(Real.java:14)

Help me. I must not use if, else, nothing. It’s a basic exercise.

1 answer

2


You can use nextLine() and then Double.parseDouble. The reason to do this is what is explaining in that other question.

Your code goes like this:

import java.io.IOException;
import java.util.Scanner;

class Real {
    public static void main(String[] args) throws IOException {
        Scanner le = new Scanner(System.in);
        System.out.println("Digite um número real");
        double real = Double.parseDouble(le.nextLine());
        System.out.println("O número digitado é: " + real);
    }
}

See here working on ideone.

However, in your statement, you speak of integers, not real numbers. In this case, you would use int:

import java.io.IOException;
import java.util.Scanner;

class Inteiro {
    public static void main(String[] args) throws IOException {
        Scanner le = new Scanner(System.in);
        System.out.println("Digite um número inteiro");
        int inteiro = Integer.parseInt(le.nextLine());
        System.out.println("O número digitado é: " + inteiro);
    }
}

See here working on ideone.

  • I have to use Parse? because for this exercise (at the time I learned I didn’t see it.. alias I only saw it last week)

  • 1

    @Carolm No, you don’t have to do this. But this is to avoid using the nextDouble and the nextInt that will cause you problems, as I explained in my answer to the other question. It’s not worth breaking your head over something like that, especially when you’re a beginner.

  • Sorry to bother you and ignore you, but if I only have to use nextDouble,?

  • 1

    @Carolm I tested your code and... It worked! See here: https://ideone.com/zoYgXu

  • our I spin in java and it gives the error that I quoted!

  • I found the error Victor! I was typing : 2.35 and not 2.35

Show 1 more comment

Browser other questions tagged

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