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行。添加完语句之后,关于资源泄漏的警告消失了,但是当我运行代码时,程序要求另一次计算的时候,右侧会弹出一个调试控制台。资源泄漏问题
我不知道为什么调试控制台会弹出,你认为问题是什么?
谢谢!帮了我很多! – Muon