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