-2

I have the below Java code. When I enter an integer value in the input, it works ok (For ex -4), but when I enter 4.0, it breaks. The error is below. Can someone please help understand what is it that I am doing wrong? Thank you in advance.

import java.util.Scanner;

public class Main {

        public static void main(String[] args ) {
            int studentAge = 25;
            double studentGPA = 3.45;
            boolean hasPerfectAttendance = true;
            String studentName = "Ivan Grey";
            char studentFirstInitial = studentName.charAt(0);
            char studentLastInitial = 'G';

                        
            System.out.println(studentAge);
            System.out.println(studentGPA);
            System.out.println(studentFirstInitial);
            System.out.println(studentLastInitial);
            System.out.println(hasPerfectAttendance);
            System.out.println(studentName);
            System.out.println(studentFirstInitial + " " + studentLastInitial + 
            " has a GPA of " +  studentGPA);
            System.out.println("What do you want to update it to?");
            
            Scanner input = new Scanner(System.in);
            studentGPA = input.nextDouble();
            input.close();
            
            System.out.println(studentFirstInitial + " " + studentLastInitial + 
            " now has a GPA of " +  studentGPA);
        }
}

Error is Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextDouble(Scanner.java:2564) at Main.main(Main.java:24)

Newbie
  • 713
  • 2
  • 10
  • 19
  • What input are you giving it? – khelwood Aug 06 '20 at 12:11
  • 4
    What is the locale of the Machine you are running the code on? (Are you from Country where comma is usually used as a decimal separator?) – OH GOD SPIDERS Aug 06 '20 at 12:18
  • @OHGODSPIDERS ---- hey, thanks a lot man! yes, that was the issue. – Newbie Aug 06 '20 at 12:34
  • Does this answer your question? [nextDouble() throws an InputMismatchException when I enter a double](https://stackoverflow.com/questions/5929120/nextdouble-throws-an-inputmismatchexception-when-i-enter-a-double) – Dafang Cao Aug 07 '20 at 02:34

1 Answers1

0

Scanner uses the number format of the system locale, so if you run this program in a computer with language set to French it expects you to write 4,0.

To make Scanner locale independent, add a call useLocale:

Scanner input = new Scanner(System.in);
input.useLocale(Locale.ROOT);
Joni
  • 108,737
  • 14
  • 143
  • 193