我只是想编写一个简单的计算器,它工作正常……
我现在想做的是包含一个“ do while”或“ while”循环以重复一条语句,直到用户输入四个基本操作符之一。我已经使用其他方法(if和switch)实现了它,但是我想简化它。
在学习如何使用scanner
和JPane
方法解析字符时,我也遇到很多问题。我可以使用Internet上的各种资源来实现,但是一种简单的方法可以使我更清楚地理解逻辑,而不仅仅是实现,将受到高度赞赏...
public class MyCalculator{
public static void main (String [] args){
// Let us code a simple calculator
char OP;
System.out.println("This is a simple calculator that will do basic calculations such as :\nAddition, Multiplication, Substraction and Division.");
// Create a scanner object to Read user Input.
Scanner input = new Scanner(System.in);
System.out.println("Enter Any positive number followed by pressing ENTER.");
int firstNum = input.nextInt();
// Need to Loop the below statement till one of the four (+,-,*,/) operator is entered.
System.out.println("Enter your choice of OPERATOR sign followed by pressing ENTER.");
OP = input.next().charAt(0);
System.out.println("Enter your Second number followed by an ENTER stroke.");
int secNum = input.nextInt();
// Various possible Resolution
int RSum = firstNum+secNum;
int RSubs= firstNum-secNum;
int RPro = firstNum*secNum;
double DPro = firstNum/secNum;
// Conditional statements for Processing
Switch (OP){
case '+': System.out.println("The Resulting sum is "+ RSum);
break;
case '-': System.out.println("The Resulting sum is "+ RSubs);
break;
case '*': System.out.println("The Resulting Product is "+ RPro);
break;
case '/': System.out.println("The Resulting Divisional product is "+ DPro);
break;
default : System.out.println("Try Again");
}
}
}
答案 0 :(得分:1)
您可以使用以下内容:
while(scanner.hasNext()) {
//some code
int number = scanner.NextInt();
}
但是我会实现一个计算器,如下所示:
int num1 = scanner.NextInt();
String op = scanner.Next();
int num2 = scanner.NextInt();
您可以按照以下步骤遍历字符串并进行检查:
for (char ch : exampleString.toCharArray()){
System.out.println(ch);
}
您还可以如下遍历字符串:
for (int i=0; i<examplestring.length(); i++) {
char c = examplestring.charAt(i);
}
您可以循环播放,直到得到+或-为止,如下所示:
char operator;
do {
char operator = scanner.next().get(0);
}while(operator != '+' || operator != '-')
您可以按以下步骤循环和打印错误消息:
char operator;
do {
char operator = scanner.next().get(0);
if(!isValidOperator(operator)) {
System.out.println("invalid operator");
}
}while(!isValidOperator(operator))
public boolean isValidOperator(char operator) {
if(operator == '+') {
return true;
} else if (operator == '-') {
return true;
}
return false;
}