그래서 지금 Java에서이 간단한 계산기로 작업하고 있습니다. 사용자가 스캐너에 "quit"을 입력하면 프로그램이 종료되기를 바랍니다. 나는 다음 줄에 내 메인 클래스의 끝 부분에 '만약'문으로이 기능을 구현하려고 :Java 코드를 수정하여 사용자가 "quit"을 입력 할 때 종료되도록하려면 어떻게합니까?
이if (input.equals("quit")) {
System.out.println("Thanks for using my program.");
System.exit(0);
}
내 IDE가 오류를 인식하지 않습니다,하지만 난 컴파일 할 때 내 프로그램을 실행하고, 스캐너에 'quit'을 입력하여 프로그램을 종료하려고하면 종료 메시지가 표시되지 않고 프로그램이 종료됩니다 (오류가 있음). 다음과 같이
내 코드는 다음과 같습니다 당신이 내 코드는 마지막으로 작동 할 수 있도록 문제가 있는지 말해 줄 수 있고 그래서 미래에 비슷한 실수를하지 않을 경우
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;
}
}
나는 그것을 감사하겠습니다! 사용자 유형 그래서 while 루프를 종료합니다 종료 할 때
은 무엇인가'input' 호출 할 수 있습니다? 'input.equals ("quit")는 어떻게 생각합니까? –
퇴장 메시지가 무엇입니까? –
@SotiriosDelimanolis 나는 "사용자가 종료 한 다음 무언가를 입력하면" –