Program that reads real number in Java

0

I have a pretty stupid question, let me say, but I do not remember what I should do to be correct. I should create a program that reads an integer and prints on the screen.

Here's what I have:

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 (I typed for example 2.35) but it gives 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 should not use if , else , nothing. It's a basic exercise.

    
asked by anonymous 04.05.2018 / 23:45

1 answer

2

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

Your code looks 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.

    
04.05.2018 / 23:53