【问题标题】:Java: Calculate more than 2 numbers in one row with arraysJava:用数组计算一行中超过2个数字
【发布时间】:2015-12-04 17:51:32
【问题描述】:

谁能帮我处理这段代码?我想计算一个数组中的元素 0,其中运算符在另一个数组中的元素 0 中,第一个数组中的元素 1 使用 for 循环。应该可以计算超过 2 个数字。抱歉英语不好。

代码如下:

package rechnerparser;
import java.util.*;

public class RechnerParser
{
    public static String rechnung,
                         regexCheck = "[\\+\\-\\*/]";

    public static float ergebnis;
    public static int anzahlOperator, anzahlZahlen;

    public static String[] Zeichenkette, operatoren;
    public static float[] konventiert;

    public static Scanner eingabe = new Scanner (System.in);

    public static void main(String[] args)
    {
        System.out.println("Geben Sie Ihre Rechnung auf einer Zeile ein z.B. 4+7/8 [+, -, *, /]");
        rechnung = eingabe.next();

        Zeichenkette = rechnung.split(regexCheck);   //save the numbers in the array "Zeichenkette"
        operatoren = rechnung.replaceAll("[\\da-zA-Z]","").split("");  //save the operator (+, -, *, /)in the array "operatoren"
        konventiert = new float[Zeichenkette.length];

        int i = 0;
        while(i < Zeichenkette.length) //convert the numbers from string array to float array
        {
            konventiert[i] = Float.parseFloat(Zeichenkette[i]);
            i++;
        }



        for (int a = 0; a < konventiert.length; a++)
        {
            ergebnis = konventiert[a] operatoren[a] (a++) konventiert[a]; //not working
////////////konventiert[0] operatoren[0]       konventiert[1]
//example:       5              +                  4           = 9
        }

        /*
        if(operatoren[0].contains("+"))                 //only with 2 numbers
        {
            ergebnis = konventiert[0] + konventiert[1];
        }
        else if(operatoren[0].contains("-"))
        {
            ergebnis = konventiert[0] - konventiert[1]; 
        }
        else if(operatoren[0].contains("*"))
        {
            ergebnis = konventiert[0] * konventiert[1];
        }
        else if(operatoren[0].contains("/"))
        {
            ergebnis = konventiert[0] / konventiert[1];
        }
        else
        {
            System.out.println("Falsches Format.");
        }
        */

        System.out.println(ergebnis);
    }
}

【问题讨论】:

    标签: java arrays for-loop calculator


    【解决方案1】:

    operatoren[a] 是字符串值,而不是 Java 运算符。

    for (int i = 0; i < konventiert.length - 1; i++) {
        switch (operatoren[i]) {
            case "*":
                result[i] = konventiert[i] * konventiert[i + 1];
                break;
            // more case statements
            default:
                // error
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      相关资源
      最近更新 更多