gpt4 book ai didi

java - 计算器输入是字符串

转载 作者:行者123 更新时间:2023-12-02 00:44:12 24 4
gpt4 key购买 nike

我想知道如何迭代一个字符串,即像“34+35=”这样的计算它循环遍历每个字符,如果该字符是数字并且下一个字符也是数字等,则会将其添加到字符串中。

import java.io.*;

public class SimpleTest{

static double operand1;
static char operator;
static boolean isnum;
static double result;
static String calc = "45+45=";
static String in = "";
public static void main(String[] argv){

SimpleCalculator calculator = new SimpleCalculator();


while (calculator.c != '=')
{
in = calculator.input(calc,operand1);
calculator.parsevalue(operand1, in);
}


System.out.println(calculator.getResult());
}

}

public String input(String calc, double operand1)
{
String in = "";
//66
//++2
for (int i = 0; i < calc.length(); i++)
{
c = calc.charAt(i);
String characterString = Character.toString(c);
if (Character.isDigit(calc.charAt(i)))
{
while (Character.isDigit(calc.charAt(i+1)))
{
characterString = characterString + Character.toString(calc.charAt(i+1));
i++;
}

in = characterString;
}
parsevalue(operand1,in);

}
return in;
}

public void parsevalue(double operand1, String in)
{

String characterString = in;
try
{

setOperand(Double.parseDouble(characterString));

if (flag == 0)

{

operand1 = (Double.parseDouble(characterString));
result = operand1;
flag = 1;
}

getResult();

}

catch (Exception e)
{
try
{
operator = c;
}
catch (Exception e2)
{
System.out.println("Enter a number");
}
}
}

public void setOperator(char operator){
this.operator = operator;
}

public char getOperator(){
return operator;
}

public void setOperand(double operand){

this.operand = operand;
}

public double getOperand(){

return operand;
}

public double getResult(){

if (getOperator() == '+')
{
result = (result + getOperand());
}
if (getOperator() == '-')
{
result = (result - getOperand());
}
if (getOperator() == '*')
{
result = (result * getOperand());
}
if (getOperator() == '/')
{
if (getOperand() == 0)
{
System.out.println("Cannot divide by zero");
}
result = (result / getOperand());
}

return result;
}

最佳答案

如果它始终采用 XXX+YYY= 格式,那么您应该使用 String 类中的方法。 replace 去掉 '=',split 得到两个数字并将它们解析为整数,然后计算值。

关于java - 计算器输入是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5444419/

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