gpt4 book ai didi

java - 需要帮助理解有关 While 循环条件语句和类型转换的一些基本 Java 概念

转载 作者:行者123 更新时间:2023-12-02 10:36:40 25 4
gpt4 key购买 nike

我只是想编写一个简单的计算器,它工作正常......

我现在想做的是包含一个“do while”或“while”循环来重复语句,直到用户输入四个基本运算符号之一。我已经使用其他方法(if 和 switch)实现了它,但我想简化它。

此外,我在学习如何在 scannerJPane 方法中解析字符时遇到了很多问题。我可以使用互联网上的各种资源来实现,但是一个简单的方法可以帮助我更清楚地理解逻辑而不仅仅是实现,我将非常感激......

    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");

}

}
}

最佳答案

你可以使用这样的东西:

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;
}

关于java - 需要帮助理解有关 While 循环条件语句和类型转换的一些基本 Java 概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242106/

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