0
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;
        }
    }
}

}

所以这是我高中作业的计算程序。它工作正常,直到要求退出程序或继续代码。即使我想退出程序,它也会在显示结果后重新启动。我认为代码末尾有问题。有人可以帮忙吗?

4

1 回答 1

4

问题在这里:

String startOver = sc.nextLine();

当您使用 读入操作数编号时nextDouble(),该方法会将其余行留在解析器/缓冲区中。

因此,当您打电话时,nextLine()您仍在阅读上一行的其余部分。这将导致您的startOver字符串为空,并且if条件也不起作用。

我建议你使用scan.next()而不是scan.nextLine()

于 2013-10-15T13:32:10.663 回答