import java.util.Scanner;
public class calc {
public static void main(String args[]) {
Scanner number = new Scanner(System.in);
double function, fnum, snum, answer;
System.out.print("Enter 1 for mult, 2 for div, 3 for add, 4 for sub: ");
function = number.nextDouble();
System.out.println("Enter first number:");
fnum = number.nextDouble();
System.out.println("Enter second number:");
snum = number.nextDouble();
if(function == 1){
answer = fnum * snum;
}
if(function == 2){
answer = fnum / snum;
}
if(function == 3){
answer = fnum + snum;
}
if(function == 4){
answer = fnum - snum;
}
System.out.println("Answer: " + answer);
}
}
5 replies to this topic
#1
Posted 20 November 2011 - 03:02 PM
I made this simple 4 function calculator but I get a run time error saying the variable "answer" isn't initialized, which it clearly is...can someone help? thanks :D
|
|
|
#2
Posted 20 November 2011 - 03:09 PM
If all 4 "if's" evaluate to false, then "answer" will never be initialized. The compiler is trying to catch this.
#3
Posted 20 November 2011 - 03:16 PM
ohh ok, that's what I thought. So if I made an else statement that restarted the program then would it work?
thanks for the quick reply btw :)
thanks for the quick reply btw :)
#4
Posted 20 November 2011 - 03:31 PM
Yup, that would work, which is probably the best choice.
Or you can initialize the "answer" variable before the if tests. Like setting it equal to -1, or Integer.MAX_VALUE, or whatever.
Or you can initialize the "answer" variable before the if tests. Like setting it equal to -1, or Integer.MAX_VALUE, or whatever.
#5
Posted 20 November 2011 - 04:09 PM
how could I tell the compiler to restart the program if function doesn't equal 1, 2, 3, or 4? I looked it up and people said to call the main method but I don't know how to do that.
#6
Posted 20 November 2011 - 06:32 PM
You could use a while loop that runs until function = 1, 2, 3, or 4. After function = 1, 2, 3, or 4 end the while loop.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









