gpt4 book ai didi

java - java中使用System.exit(0)退出程序

转载 作者:行者123 更新时间:2023-12-01 14:01:42 26 4
gpt4 key购买 nike

我对如何实现 System.exit(0); 有点困惑在我的程序中。我想要发生的是用户输入“exit”一词并让程序终止。我还希望程序在输入“clear”时返回“0.0”,但我认为我在处理变量时遇到问题,因为 num1 和 num2 是 double ,但我希望“exit”和“clear”是可接受的输入,也是如此。

如果有人有任何见解,我们将不胜感激。这是我的代码:

package projectapcs;

/**
*
* @author Apple
*/

import java.util.Scanner;

public class ProjectAPCS {

public static void exit(int x){

}

public static void clear(int y){

}

public static void main(String[] args) {



double num1;
double num2;
char char1;
String operation;


Scanner input = new Scanner(System.in);

System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");


System.out.println
("\nEnter the first number:");
num1 = input.nextInt();



System.out.println
("Display:" + num1);

System.out.println("Please enter operation:");
operation = input.next();



System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);





if ("+".equals(operation)){

System.out.println((num1 + num2));
}
else if ("-".equals(operation)){

System.out.println((num1 - num2));
}
else if ("/".equals(operation)){

System.out.println((num1 / num2));
}
else if ("*".equals(operation)){

System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){

System.out.println (-num1);
}
else if ("x^2".equals(operation)){

System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){

System.out.println (Math.sqrt(num1));

}


else if ("H".equals(num1)){

System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}

else if("E".equals(num1)){

System.out.println ("Calculator program terminated...");
System.exit(0);
}

}

}

最佳答案

如果您想允许任意输入,请将输入读取为字符串,然后 convert to double根据需要:

String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}

关于java - java中使用System.exit(0)退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19308938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com