使用传入的args执行计算作为我的计算器的inputString

时间:2022-12-23 21:24:11

If I run my calculator I want it to start to calculate automatically with the given args e.g. 4+4-2. When there are no args he just asks for the user to insert numbers (scanner). Here is my code.So the args need to be assigned to my inputString if there are nog args the scanner will ask the user to isert something.

如果我运行我的计算器,我希望它开始使用给定的args自动计算,例如4 + 4-2。当没有args时,他只是要求用户插入数字(扫描仪)。这是我的代码。因此,如果存在nog args,扫描器将要求用户输入isgot,则需要将args分配给我的inputString。

Main

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 userInput = new Scanner(System.in);

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

    inputString = userInput.next();

    userInput.close();

    Calculator calculator = new Calculator();

    calculator.startCalculator(inputString);

  }// end of main
}// end of class

calculator

package com.haynespro.calculator;

import java.util.ArrayList;

public class Calculator {

 public void startCalculator(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("\nLet 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

private 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 == '/';
}

}

2 个解决方案

#1


1  

change your main by using args (also some refactoring in the main class):

通过使用args(在主类中也进行一些重构)来改变你的主要内容:

public static void main(String[] args) {
    String input=null;
    if(args.length>0){
        input=args[0];
        System.out.println(input);
    }else{
        input=askForInput();
    }

    Calculator calculator = new Calculator();

    calculator.startCalculator(input);

}// end of main

private static String askForInput() {
    // inputString with scanner
    Scanner userInput = new Scanner(System.in);
    System.out.print("please insert your calculations: ");
    String inputString;
    try {
        inputString = userInput.next();
    } finally {
        userInput.close();
    }
    return inputString;
}

#2


1  

You are not validating args.length to figure out how many parameters have been passed in.

您没有验证args.length来确定传入了多少参数。

I will give you a simplified version since I don't have any idea how you are supposed to read/parse args.

我会给你一个简化版本,因为我不知道你应该如何阅读/解析args。

String input;

if (args.length < 1) {
    // you need a Scanner to read an input for the calculator
    input = new Scanner(System.in).nextLine();
} else {
    // you've got args to parse
    input = String.join("", args);
}

new Calculator().startCalculator(input);

#1


1  

change your main by using args (also some refactoring in the main class):

通过使用args(在主类中也进行一些重构)来改变你的主要内容:

public static void main(String[] args) {
    String input=null;
    if(args.length>0){
        input=args[0];
        System.out.println(input);
    }else{
        input=askForInput();
    }

    Calculator calculator = new Calculator();

    calculator.startCalculator(input);

}// end of main

private static String askForInput() {
    // inputString with scanner
    Scanner userInput = new Scanner(System.in);
    System.out.print("please insert your calculations: ");
    String inputString;
    try {
        inputString = userInput.next();
    } finally {
        userInput.close();
    }
    return inputString;
}

#2


1  

You are not validating args.length to figure out how many parameters have been passed in.

您没有验证args.length来确定传入了多少参数。

I will give you a simplified version since I don't have any idea how you are supposed to read/parse args.

我会给你一个简化版本,因为我不知道你应该如何阅读/解析args。

String input;

if (args.length < 1) {
    // you need a Scanner to read an input for the calculator
    input = new Scanner(System.in).nextLine();
} else {
    // you've got args to parse
    input = String.join("", args);
}

new Calculator().startCalculator(input);