I was trying to write a simple calculator in java, becouse I would like to learn this language. But I am not able to calculate the “C” variable. Please help. What’s wrong?
import java.util.*;
//Simple calculator
public class calc
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double a, b, c;
System.out.print("Write first number");
a = in.nextDouble();
System.out.print("and write second");
b = in.nextDouble();
System.out.print("Choose the operation 1.Addition 2.Subtraction >Please write the number of operation ");
double somethin = in.nextDouble();
int addition = 1;
int subtraction = 2;
if (somethin >= addition)
{
c = a + b;
}
else if (somethin >= subtraction)
{
c = a - b;
}
{
System.out.println(c);
}
}
}
The problem is that you need to assign an initial value to the c variable. In Java, any time you use the value of a local variable, Java insists that it must be set to something. Since you print out the value of c at the bottom of the program, but set its value inside of a conditional, Java does not know for sure if one of those conditionals will be executed before the value of c gets used in the System.out statement. The way to fix this is to either add an “else” to the conditional that also assigns a value to c, or set its value at some other point that is guaranteed to execute (such as when you create it).
For example, changing your code to say
will make the compile error go away. But, as others have noted, there are other issues with the code as well.