PDA

View Full Version : help!simple coding problem..


nicky_85
02-20-2009, 06:07 PM
im doing a practical, which asks the user to enter two numbers and print the sum, product, difference and division of the numbers.following is my code:

import java.util.*;
class Testing{
public static void main (String [] args){
Scanner s=new Scanner(System.in);
System.out.println("Pls enter the 1st num");
int a =s.nextInt();
System.out.println("Pls enter the 2nd num");
double b=s.nextDouble();

System.out.println("The sum is :" + (a+b));
System.out.println("The division is :" + (a/b));
System.out.println("The different is :" + (a-b));
System.out.println("The product is :" + (a*b));
}
}

this program can run, but my question is:
1) for different, if num a < num b, negative will appear, how if i dunwan the negative appear?
2) i wan to make the answer for division become 2 decimal, how to solve it?

hope somebody can guide me.thx!

brad211987
02-20-2009, 06:58 PM
For the difference, you could get the absolute value using the java.lang.Math class.

To get decimal results, you will need to use a different type of number. Use a double or float for both numbers, or type cast the int variable to a double or float.

nicky_85
02-20-2009, 07:20 PM
thx ya~u r so kind~