将我的大部分代码放在另一个类中,如何使其在Eclipse中起作用?

时间:2018-09-20 07:36:52

标签: java eclipse class

我在一个班级文件中做了一个计算器,它工作正常。 现在,我决定只让我的输入字符串和扫描程序在主类中,而其余代码进入另一类。如何使其运作?请注意,我是初学者。因此,主类也需要运行/执行计算器类。

我在计算器课上收到的错误是:

  • inputString无法解析为变量
  • 重复的字段Calculator.i(我的循环)
  • 以及关于这些符号(,),;。
  • 的许多语法错误

主类

package com.haynespro.calculator;

import java.util.Scanner;


public class CharAtExample {

    public static void main(String[] args) {

        for (String arg:args) {
            System.out.println(arg);
        }

        // inputString with scanner

        String inputString = "0";

        inputString = inputString.replace(",", "");

        Scanner user_input = new Scanner(System.in);

        System.out.print("please insert your calculations: ");

        inputString = user_input.next();

        user_input.close();


        }
    }
}

计算器类

package com.haynespro.calculator;

import java.util.ArrayList;


public class Calculator {

    // Assign ArrayList of Strings "res" to splitExpression

    ArrayList<String> res = splitExpression(inputString);

    // Create an ObjectList that holds res

    ArrayList<Object> objectList = new ArrayList<Object>(res);

    System.out.print("\n Let my algorithm take care of it: \n\n");

    // Loop through the objectList and convert strings to doubles

    for (int i = 0; i < objectList.size(); i++) {
        try {
            objectList.set(i, Double.parseDouble((String) objectList.get(i)));
        } catch (NumberFormatException nfe) {

        }
    }

    // Create a variable maxi to substract 2 from the objectList index

    int maxi = objectList.size();

    maxi = maxi - 2;

    // Create variable lastSum out of the incoming for-loop's scope.

    double lastSum = 0;

    // Loop through the objectList with an algorhitm and perform calculations with
    // invoking the sum method

    for (int i = 0; i < maxi; i += 2) {
        String operator = (String) objectList.get(i + 1);
        double a = (Double) objectList.get(i);
        double b = (Double) objectList.get(i + 2);
        double sum;

        if (i == 0) {
            sum = sum(a, b, operator);
        } else {
            sum = sum(lastSum, b, operator);
        }
        lastSum = sum;
        System.out.println(lastSum);
    }

    // Method that matches the string input with operators to perform calculations.

    public static double sum(Double a, Double b, String operator) {

        if (operator.equals("+")) {
            return a + b;
        }
        if (operator.equals("-")) {
            return a - b;
        }
        if (operator.equals("*")) {
            return a * b;
        }
        if (operator.equals("/")) {
            return a / b;
        }
        return 0;
    }

    // ArrayList splitExpression that casts to inputString

    public static ArrayList<String> splitExpression(String inputString) {

        // ArrayList result to return the result

        ArrayList<String> result = new ArrayList<String>();

        // Uses the toCharArray method to insert the string reference per character into
        // an array

        char[] destArray = inputString.toCharArray();

        // Empty String created

        String token = "";

        // Iterate through the "Items" in the Array

        for (int i = 0; i < destArray.length; i++) {

            // Nice all those references but we need an Object that actually holds the array

            char c = destArray[i];

            // If not a number then add to token, else assign the value of c to token

            if (isBreakCharacter(c)) {
                result.add(token);
                result.add(Character.toString(c));
                token = "";
            } else
                token = token + c;
            }

            result.add(token);
            return result;
        }
    }

    // a method that breaks characters which are not numbers.The object "c" also
    // needs to hold this method.

    public static boolean isBreakCharacter(char c) {
        return c == '+' || c == '*' || c == '-' || c == '/';
    }
}

1 个答案:

答案 0 :(得分:1)

您需要将代码放在类内部的方法中。例如:

public static void doStuff(String inputString) {
    // Assign ArrayList of Strings "res" to splitExpression
    ArrayList<String> res = splitExpression(inputString);
    // Create an ObjectList that holds res
    ArrayList<Object> objectList = new ArrayList<Object>(res);
    System.out.print("\n Let my algorithm take care of it: \n\n");

    // (...)  REST OF YOUR CODE

    for (int i = 0; i < maxi; i += 2) {
        String operator = (String) objectList.get(i + 1);
        double a = (Double) objectList.get(i);
        double b = (Double) objectList.get(i + 2);
        double sum;

        if (i == 0) {
            sum = sum(a, b, operator);
        } else {
            sum = sum(lastSum, b, operator);
        }
        lastSum = sum;
        System.out.println(lastSum);
    }
}

现在,方法doStuff具有参数String inputString(它解决了您的第一个问题 inputString无法解析为变量)。所有其他语法错误现在也应该消失。

在您的main方法中,您将像这样调用该方法:

public static void main(String[] args) {
    String inputString = "0";

    // the code with the scanner comes here...

    doStuff(inputString);
}

另一个提示:扫描程序可能会引发异常-因此您需要try.. catch。由于您最后“关闭”了扫描仪,因此可以使用较短的尝试使用资源,如下所示:

try (Scanner user_input = new Scanner(System.in)) {         // the scanner is only available inside the try block - and in each case (exception or not) it will be closed.
    System.out.print("please insert your calculations: ");
    inputString = user_input.next();
}

last 提示:在循环中,您有一个try...catch捕获了NumberFormatException。处理异常最好。例如,为用户打印一条消息,以便他知道发生了什么或设置默认数字...

希望这会有所帮助