0

I'm working on a very simple tax calculator in java to see where my skills are at after some basic lessons, and I have the basic functionality down but I'm trying to make the calculator able to deal with an error without crashing. Here's what my code looks like:

import java.util.Scanner;

public class Application {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Please enter the principle");

        float principle = scanner.nextFloat();

        System.out.println("Your total with tax is: " + principle * 1.07);

So I run my code and it works out properly adding in 7% tax to whatever the principle entered is, but the program crashes when a letter or anything that isn't a number is entered. Ideally, I'd like to have it display something like "Please enter a number" if anything other than a number is entered. How should I go about doing this?

Jason
  • 11,258
  • 3
  • 39
  • 46

2 Answers2

0

You have to validate the scanner input before doing the math, try to convert the string into float,

try
    {
      float f = Float.valueOf(scanner.next....);
      System.out.println("float f = " + f);
      System.out.println("Your total with tax is: " + principle * 1.07);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

What you need to do is exception handling.

When the user enters something that cannot be parsed to a float, it throws an exception, which is why your program crashed. To handle this exception, you just need to surround the code where the exception might happen. In this case, it is:

    float principle = scanner.nextFloat();

    System.out.println("Your total with tax is: " + principle * 1.07);

You should change it to :

try {
    float principle = scanner.nextFloat();
    System.out.println("Your total with tax is: " + principle * 1.07);
}

Then, you need to add a catch block to specify what should be done when the exception did occur.

try {
    ...
} catch (NumberFormatException ex) {
    System.out.println("Input Invalid");
}

Here I wrote NumberFormatException because when it cannot parse a float, a NumberFormatException (specifically) would occur.

The whole code is:

try {
    float principle = scanner.nextFloat();

    System.out.println("Your total with tax is: " + principle * 1.07);
} catch (NumberFormatException ex) {
    System.out.println("Input Invalid");
}
Sweeper
  • 145,870
  • 17
  • 129
  • 225