Function for calculating with decimal places

This code works fine when you type, for example, 22 and 56, it shows the correct result

  import java.util.Scanner;

class apples{
    public static void main(String args[]){
    Scanner villy = new Scanner (System.in);
    double fnum, snum, answer;
    System.out.println("Enter first num: ");
    fnum = villy.nextDouble();
    System.out.println("Enter second num: ");
    snum = villy.nextDouble();
    answer = fnum + snum;
    System.out.println(answer);
    }
}

but when you try to put decimals like 23.53 and 42.76 for example, it crashes with the following exception

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 apples.main(apples.java:8)
+3
source share
4 answers

Are you on a non-jengine computer by any chance? For example, with French or German, you need to enter 23,53, not 23.53.

The default locale for the scanner is what Locale.getDefault () returns: on an English computer, it should return Locale.ENGLISH. You can set the locale to English by following these steps:

Scanner villy = new Scanner(System.in).useLocale(Locale.ENGLISH);
+1

API .

InputMismatchException:

, ,

, ; , "" - .

, , , API. , Eclipse , . :

Scanner villy = new Scanner("23.53\n42.76\n");

, ; , , Eclipse.

, , , - . , , , , , - . Eclipse , , . .

, , Java, . , , ( String).

+1

, . InputMismatchException. , , InputMismatchException, .

+1
source

The following code snippet works fine. Your problem should lie elsewhere. What do you mean by the word "this fails"? Does it provide an error message or an exception?

double fnum=0, snum=0, answer = 0;
fnum=23.53;
snum=42.76;
answer=fnum+snum;
System.out.println("answer="+answer); //prints 66.28999999999999
0
source

Source: https://habr.com/ru/post/1759980/


All Articles