Reputation: 71
class Operation {
double add(double a, double b){
double c;
c = a+b;
return c;
}
double sub(double a, double b){
double c;
c = a-b;
return c;
}
double mul(double a, double b){
double c;
c = a*b;
return c;
}
double div(double a, double b){
double c;
c = a/b;
return c;
}
}
class Selection{
static double x,y;
void sel(int a){
Operation op = new Operation();
Scanner sc = new Scanner(System.in);
char b;
if(a==1)
b='+';
else if(a==2)
b='-';
else if(a==3)
b='*';
else
b='/';
System.out.println(">>You have selected "+b+" operator");
System.out.println(">>Please enter the first operand.");
x = sc.nextDouble();
System.out.println(">>Please enter the second operand.");
y = sc.nextDouble();
}
double x(){
return x;
}
double y(){
return y;
}
}
public class Calculator {
static int select;
public static void main(String [] args){
Operation op = new Operation();
Selection se = new Selection();
Scanner sc = new Scanner(System.in);
boolean run = true;
while(run){
System.out.printf(">>Select Operator\n>>1: + 2: - 3: * 4: /\n");
select = sc.nextInt();
if(select == 1){
se.sel(1);
double a = se.x();
double b = se.y();
double result = op.add(a, b);
System.out.println(">>The result of "+a+" + "+b+" is "+result);
}else if (select ==2){
se.sel(2);
double a = se.x();
double b = se.y();
double result = op.sub(a,b);
System.out.println(">>The result of "+a+" - "+b+" is "+result);
}else if (select ==3){
se.sel(3);
double a = se.x();
double b = se.y();
double result = op.mul(a,b);
System.out.println(">>The result of "+a+" * "+b+" is "+result);
}else if(select == 4){
se.sel(4);
double a = se.x();
double b = se.y();
double result = op.div(a,b);
System.out.println(">>The result of "+a+" / "+b+" is "+result);
}else {
System.out.println(">>Your number is not available, please try again!");
System.out.println();
System.out.println();
continue;
}
System.out.println(">>Do you want to exit the program(y/n)?");
String startOver = sc.nextLine();
if(startOver.equals("y")){
run = false;
System.out.println(">>Thank you for using my program!");
}else{
continue;
}
}
}
}
So this is my calculation program for a high school homework. It works fine until, asking for quitting the program or keep continuing the code. Even if I want to quit the program, it restarts after showing the results. I think there's something wrong at the end of the code. Can somebody help?
Upvotes: 0
Views: 143
Reputation: 1430
The problem is here:
String startOver = sc.nextLine();
When you read in the operand numbers with nextDouble()
, the method leaves rest of the line in the parser/buffer.
So when you call nextLine()
you are still reading the rest of the previous line.
This will cause your startOver
string to be empty and the if
condition doesn't work as well.
I suggest you to use scan.next()
instead of scan.nextLine()
Upvotes: 4