所以我一直在Java中使用這個簡單的計算器一段時間,並且我希望程序在用戶在掃描器中輸入「quit」時結束。我試圖實現此功能爲我的附近在以下行主類的末尾的「如果」語句:如何修復我的Java代碼,以便在用戶輸入「quit」時結束?
if (input.equals("quit")) {
System.out.println("Thanks for using my program.");
System.exit(0);
}
我的IDE不承認任何錯誤,但是當我編譯和運行我的程序,嘗試通過在掃描儀中鍵入「退出」退出程序,程序結束(帶有錯誤)而不顯示退出消息。
我的代碼如下:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("If you want to continue, hit enter.");
String s1 = scan.nextLine();
if (s1.equals("help")){
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b')");
System.out.println("Subtraction: '-' (Ex: 'a - b')");
System.out.println("Multiplication: '*' (Ex: 'a * b') ");
System.out.println("Division: '/' (Ex: 'a/b')");
System.out.println("Exponents: '^' (Ex: 'a^b')");
System.out.println(" ");
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA, numB;
char operator;
boolean quit = false;
while (quit == false) {
System.out.print("Please enter your equation: ");
numA = input.nextDouble();
operator = input.next().charAt(0);
numB = input.nextDouble();
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
System.out.println(answer);
if (input.equals("quit")) {
System.out.println("Thanks for using my program.");
System.exit(0);
}
}
input.close();
}
}
class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
}
我將不勝感激,如果你能告訴我什麼是錯了,所以我的代碼最終會工作,所以,我不會讓類似的錯誤在未來!
在此先感謝
什麼是'input'?你認爲'input.equals(「quit」)'做了什麼? – 2014-10-22 01:35:20
你的退出信息是什麼? – 2014-10-22 01:36:00
@SotiriosDelimanolis我認爲這意味着「如果用戶輸入退出,然後做一些事情」 – 2014-10-22 01:37:25