私はプログラミングとjavaを初めて使用しており、正しく動作することがありますが、矛盾していることがあります。私は特定の値で一度それを実行し、直接前と同じ正確な入力で再実行しようとしました。次回以降は動作しません。この信頼性をいかに修正するかを教えてください。私は自分のコードでこれの理由を見つけることができません。助けてください。正確に同じ入力値でプログラムが予期せず実行される
import java.util.*;
public class Calculator {
public static void main(String[] args) { //void
boolean done = false;
Scanner console = new Scanner(System.in);
while (!done){
displayMenu();
String selection = getUsersSelection(console);
done = processSelection(selection, console);
//caluculateResults(console);
}
System.out.println("Thank you for using this program");
}
private static boolean processSelection(String selection, Scanner console) {
boolean done = false;
if (!selection.equalsIgnoreCase("Q")){
if (selection.equalsIgnoreCase("U")){
caluculateResults(console);
}
else if (selection.equalsIgnoreCase("H")){
}
else {
System.out.println("Incorrect entry...try again!");
}
}
else {
done = true;
}
return done;
}
private static void caluculateResults(Scanner console) {
displayCalculatorInstructions();
double operand1 = console.nextDouble();
char operator = console.next().charAt(0);
double operand2 = console.nextDouble();
double result = 0.00; //double from int
boolean isOperatorValid = true;
if (operator == '+'){
result = operand1 + operand2;
}
else if (operator == '-'){
result = operand1 - operand2;
}
else if (operator == '*'){
result = (double) operand1 * (double) operand2;
}
else if (operator == '/'){
if (operand2 != 0.00){
result = operand1/operand2;
}
else {
result = (int)Double.NaN;
}
}
else if (operator == '^'){
result = Math.pow(operand1, operand2);
}
else {
isOperatorValid = false;
System.out.println("Invalid operator");
}
if (isOperatorValid){
System.out.println("The result of your operation is: ");
System.out.printf(operand1 +" "+operator+" "+operand2+" = %5.3f", result);
System.out.println();
}
}
private static void displayCalculatorInstructions() {
System.out.println("Enter a mathematical expression to evaluate");
System.out.println("Valid operations are: +, -, /, *,^for power");
System.out.println("Expression are entered with spaces between the values and operator");
System.out.println("Here is the valid format:");
System.out.println("\t<value><space><operator><space><value>");
System.out.print("Your expression: ");
}
private static String
private static void displayMenu() {
System.out.println("Enter one these options:");
System.out.println("\tH for Help");
System.out.println("\tU for using calculator");
System.out.println("\tQ for exiting this program");
System.out.print("Your selection: ");getUsersSelection(Scanner console) {
String selection = console.next();
return selection;
}
}
}
'この不確かさを修正する'私はあなたが本当にこの動作を見ているのか疑問です。どちらの場合も同じ入力が正確に入力されていることは確かですか? –
私はあなたのコードを実行し、その正常に動作しています。あなたは信頼できない答えを得ている入力を教えてくれますか? –
出力結果がどのように変化するのか不思議です。たとえば、私の入力は12.2^3でした。初めての出力は1815.848で、2度目は無効な入力警告を受け取りました。 – Elea