Reputation: 1
I'm very new to Java (Just started this afternoon), and I've been trying to build a simple conditional calculator using switch statements.
The code I'm trying to make is quite simple. At first, ask for user's input (Statement), then the first number, and the second number.
The correct calculations will be made in accordance to the value of the input (If it's 'Sum', then it'll be first number + second number. 'Sub' then first number - second number,...).
import java.util.Scanner;
class Scalc{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//Variables//
double fnum, snum, anum; //(First Number, Second Number, Answer Number)//
String statement;
//Input//
System.out.println("Enter Statement: ");
statement = input.nextLine();
System.out.println("Enter First Number: ");
fnum = input.nextDouble();
System.out.println("Enter Second Number: ");
snum = input.nextDouble();
//Decision//
switch (statement){
case "Sum":
anum = fnum + snum;
System.out.println(anum);
break;
case "Sub":
anum = fnum - snum;
System.out.println(anum);
break;
case "Mul":
anum = fnum * snum;
System.out.println(anum);
case "Div":
anum = fnum / snum;
System.out.println(anum);
break;
default:
System.out.println("STATEMENT UNDEFINED");
break;
}
}
}
Right now, though, it's stuck at 'Sub', for subtraction.
The programme runs normally, but when I input 'Mul', instead of multiplying the number, it subtracts instead. Same goes for 'Div'. Technically, the code seems to be stuck at subtraction and can't get any farther than that.
I'm still a noob at this so ...
Anyone?
Upvotes: 0
Views: 72
Reputation: 37404
You need to add break
in under Mul
case otherwise your next case
statements will keep on executing until end of switch
or break
case "Mul":
anum = fnum * snum;
System.out.println(anum);
break;
Upvotes: 4