Java 基本 CLI 计算器
Java basic CLI calculator
我想制作用于基本数学运算的计算器。如果用户输入任何其他字符而不是 /,*,-,+ 程序应该退出。但用户只能通过输入其他字符退出。程序必须重新显示主菜单。
我试了很多次只通过数学运算。但我想不出办法。
这是我的代码
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));
}
}
我不会敲代码,但我会写出大概的思路。首先有一个 while 循环,它将获取操作员。如果运算符有效,则执行 break;
否则将重复输入。只需这样做即可解决您的问题。其余代码将随之而来。注意范围(即在括号内声明变量)。
编辑:
如果你想中断程序,只需添加一个 if 语句 if (!(operator.equals("*") || operator.equals("+") ...
等。另外,如果你真的想要漂亮的设计,你可以使用哈希集来存储操作。
我想制作用于基本数学运算的计算器。如果用户输入任何其他字符而不是 /,*,-,+ 程序应该退出。但用户只能通过输入其他字符退出。程序必须重新显示主菜单。 我试了很多次只通过数学运算。但我想不出办法。
这是我的代码
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));
}
}
我不会敲代码,但我会写出大概的思路。首先有一个 while 循环,它将获取操作员。如果运算符有效,则执行 break;
否则将重复输入。只需这样做即可解决您的问题。其余代码将随之而来。注意范围(即在括号内声明变量)。
编辑:
如果你想中断程序,只需添加一个 if 语句 if (!(operator.equals("*") || operator.equals("+") ...
等。另外,如果你真的想要漂亮的设计,你可以使用哈希集来存储操作。