положить большую часть моего кода в другой класс, как позволить ему функционировать в Eclipse? - PullRequest
0 голосов
/ 20 сентября 2018

Я сделал калькулятор в одном файле класса, и он работал нормально.Теперь я решил разрешить только мою входную строку и сканер в основном классе, а оставшийся код - в другой класс.Как заставить это работать?Обратите внимание, что я новичок.Таким образом, основной класс также должен запускать / выполнять класс калькулятора.

Ошибки, которые я получаю в классе калькулятора:

  • inputString не может быть преобразована в переменную
  • Повторяющееся поле calculator.i (my for loop)
  • и еще много синтаксических ошибок относительно этих символов (,),;,.

Основной класс

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 голосов
/ 20 сентября 2018

Вам нужно поместить код в метод внутри вашего класса.Например:

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

И последняя подсказка: Вваш цикл у вас есть try...catch, который ловит NumberFormatException.Было бы лучше, когда вы обрабатываете исключение.Например, напечатать сообщение для пользователя, чтобы он знал, что произошло, или установить номера по умолчанию ...

надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...