0

I am new to JAVA and programming in general. So please be patient with this. I am trying to output the PI in 2 decimal places, however when I input 3.14 I get an

Exception in thread "main" java.util.InputMismatchException

I feel like I am close and that I just need to adjust the code very little for this to work. I have scanned the forums for a couple of days and can't seem to get it to work. Any explanation / help would be appreciated!

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.println("What is the value of PI to two decimal places? : ");
  int pi = sc.nextInt();
  System.out.println("PI is: " + pi);
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
jheath
  • 11
  • 1
  • 3

2 Answers2

0

You should scan a double, not an int. And you should format it two get 2 decimal places.

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println( "What is the value of PI to two decimal places?:");
    double pi = sc.nextDouble();
    DecimalFormat df = new DecimalFormat("#.00");
    String piStr = df.format( pi);
    System.out.println("PI is: " + piStr);
}
uoyilmaz
  • 3,035
  • 14
  • 25
0

"3.14" isn't an Integer so when you reach

int pi = sc.nextInt();

You raise

Exception in thread "main" java.util.InputMismatchException

You should change your code and try:

Scanner sc = new Scanner(System.in);
    System.out.println("What is the value of PI to two decimal places? : ");
    double pi = sc.nextDouble();
    System.out.println("PI is: " + pi);
    }

Result:

What is the value of PI to two decimal places? : 
3,14
PI is: 3.14
Erwan C.
  • 709
  • 5
  • 18