# How to subtract numbers with decimals with Java?

• 01-27-2013, 01:19 AM
coding
How to subtract numbers with decimals with Java?
Everytime I enter a number to subtract with a decimal I get an error. The code ask for a number I enter a decimal number like 5.5 and it gives me an error and I want to be able to subtract them.
• 01-27-2013, 01:52 AM
Fubarable
Re: How to subtract numbers with decimals with Java?
• 01-27-2013, 02:43 AM
coding
Re: How to subtract numbers with decimals with Java?
Quote:

public class s {
public static void main(String[] args)
{
int a ;
int b ;
int sub;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
a=input.nextInt(); // store the input a.
b=input.nextInt(); // store the input in b.

sub = a - b; //subtract the 2 two numbers

System.out.println("Your change is : " + sub); // display the result of the two numbers

}
}
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at s.main(s.java:13)

And when I enter normal numbers its fine, but when i enter decimals like 10.5 i get an error and idk how it can break up the answers in dollars, quartiers, dimes and pennies.
• 01-27-2013, 02:47 AM
Fubarable
Re: How to subtract numbers with decimals with Java?
You're using your Scanner object to read in an int, since that's what it's nextInt() method logically does. If you try to enter a non-int number, it makes sense that this will cause an error. There are other Scanner methods available, but rather than just give you the solution, I would prefer inviting you to check the Scanner API, since extracting this information from the API is a useful and necessary skill if you're to program in Java. Please have a look at the method list for this class, in particular the nextXXX() series of methods, and see if one may be more appropriate for your purposes. Much luck, and come back if still stuck.

Edit: also, when posting code in the forum, please try to wrap the code in [code] [/code] tags, not [quote] [/quote] tags as you've done above. This will make your code much easier to read.