import java.util.Scanner;
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 func(int a){
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();
sc.close(); //line 44, this statement gave me a problem.
}
}
public class Calculator {
static int select;
@SuppressWarnings("static-access")
public static void main(String [] args){
Operation op = new Operation();
Selection sel = 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();
double a = sel.x;
double b = sel.y;
double result;
switch(select){
case 1:
sel.func(1);
a = sel.x;
b = sel.y;
result = op.add(a, b);
System.out.println(">>The result of "+a+" + "+b+" is "+result);
break;
case 2:
sel.func(2);
a = sel.x;
b = sel.y;
result = op.sub(a,b);
System.out.println(">>The result of "+a+" - "+b+" is "+result);
break;
case 3:
sel.func(3);
a = sel.x;
b = sel.y;
result = op.mul(a,b);
System.out.println(">>The result of "+a+" * "+b+" is "+result);
break;
case 4:
sel.func(4);
a = sel.x;
b = sel.y;
result = op.div(a,b);
System.out.println(">>The result of "+a+" / "+b+" is "+result);
break;
default:
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)?");
String startOver = sc.next();
if(startOver.equals("y")){
run = false;
System.out.println(">>Thank you for using my program!");
}else{
System.out.println();
continue;
}
sc.close(); //line 111, this works fine i think.
}
}
}
我是 Java 编程的初学者,这是我作业的简单“计算器”代码。我希望我的代码简单而有效,并且非常努力。检查代码后,弹出一条警告消息说“资源泄漏:'sc'从未关闭”。我知道不添加“sc.close();”它仍然可以正常运行,但我希望我的程序是完美的并添加了“sc.close();” 语句到第44行和第111行。添加语句后,关于资源泄漏的警告消失了,但是当我运行代码时,程序有时会要求再次计算,就在那里,一个调试控制台弹出。
我不确定为什么会在那里弹出调试控制台,您认为问题是什么?