我想为基本的数学运算做计算器。如果用户输入任何其他字符而不是/,*, - ,程序应该退出。但用户只能输入其他字符才能退出。程序必须重新显示主菜单。 我尝试过很多次才能通过数学运算。但我想不出办法做到这一点。Java基本CLI计算器
这是我的代码
package com.cv;
import java.util.Scanner;
class Q_04 {
public static double math(double x, double y, char a) {
if (a == '/') {
return x/y;
} else if (a == '*') {
return x * y;
} else if (a == '+') {
return x + y;
} else if (a == '-') {
return x - y;
}
return a;
}
public static void main(String[] argv) {
System.out.println(
"\t*:For multiplication\n\t/:For division\n\t+:For addition\n\t-:For substraction\n\tAny other character:To exit mathematical operation");
Scanner sc = new Scanner(System.in);
String z = sc.nextLine();
char a = z.charAt(0);
System.out.print("Enter Number 1: ");
double x = sc.nextDouble();
System.out.print("Enter Number 2: ");
double y = sc.nextDouble();
double result = 0;
System.out.println("Answer is " + math(x, y, a));
}
}
你的问题不清楚。 – Gendarme
修复问题中的代码以使其可读(即缩进并使用文本函数代码),它将使人们更容易阅读它。 – MathBunny
对不起,格式不好我的意思是我想做除了乘法,除法和减法的数学运算。如果用户输入其他字符程序应该退出。 – nascar895