Katana24
Katana24

Reputation: 8959

What is best practice for handling input in a command-line based calculator program?

Yo - trying to get back into java so decided to create a calculator.

It's suppose to work like this:

1) Get input from the user in the form of a string -> This input is stored as a string, for example: 12+89

2) Split the string according to operator position and ensure that whatever comes before this operation is converted to an integer and stored

3) Once string has been passed through, compute the value

Im pretty sure Im making this more complicated than what it actually is :p here is the code so far:

// Split String, count digits in string
public static void spitStrg() {
    int numDigits = 0;
    int numOperators = 0;
    for (int i = 0; i < input.length(); i++) {
        if (Character.isDigit(input.charAt(i))) {
            numDigits++;
        }
        else if (input.charAt(i) == '+') {
            System.out.println( "Position of operator: "+i);
            numOperators++;
        }
    }
    System.out.println("Number of Digits: "+numDigits);
    System.out.println("Number of Operators: "+numOperators);
}

// Create a number from cut off point
public static void createNum(int startPoint, int operatorPosition) {
    String tempNum = "";

    for (int j = startPoint; j < operatorPosition; j++) {
        tempNum = tempNum + input.charAt(startPoint);
    }
}

Does anyone have any other suggestions on how to handle this? I.e. ask for one number at a time and then the operator or store everything in a vector to reflect a growing number of digits and operators?

Upvotes: 1

Views: 814

Answers (5)

cl-r
cl-r

Reputation: 1264

Have a look in Enum class in Effective Java, book bu Joshua Bloch to manage operator by yourself

If you have limited operations you can use

String[] readInput = inputString.split("+|-|*|/|%").trim();

Then operator are between numbers
- numberOne is from zero to size of readInput [0]
- numberTwo beginning is done by inputString.index(readInput[1]) + readInput[1].length

Operator can be found in inputString.subtring(endOfReadInput[0],indexOfReadInput[1]).trim();

This exercise is interesting to know how split, substring and other String tools are powerful, and to understand new Enum.class possibilities, then you can read other links to understand how Pattern Design can be used

Upvotes: 1

Kareem
Kareem

Reputation: 844

I wouldn't force the user to enter the whole string, that's a bad experience. Why not do it like a normal calculator? Calculate result on the fly as the input comes in. So entering a new operator completes the current operation.

So read character by character - something like this in an infinite loop.

while(Character.isDigit(input.charAt(0)) {
    operand += digitPosition*input.charAt(0);
    digitPosition*=10;
}

digitPosition = 1;

//broke out of loop - operator received
if (isValidOperator(input.charAt(0))) {
    //store operator and await another operand (if first operation only), compute result, or throw invalid operator exception
}

Upvotes: 0

Tim Lamballais
Tim Lamballais

Reputation: 1054

If you don't want to use a library for parsing your mathematical expressions (which would be the easiest way by far, my answer will assume you don't want this) you need actual parsing, not just String splitting.

Before starting off I would advise you to read up on the basics of language parsing, specifically parsing basic arithmetic. For starters, you could read this pdf.

Upvotes: 0

Kent
Kent

Reputation: 195109

not sure if this is ok for you. (or a cheat?)

you just let user input the whole expression as a string. 23+33-34*2^2

then you could :

try {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        final Object result = engine.eval("23+33-34*2^2");
        System.out.println(result);
    } catch (final ScriptException e) {

        e.printStackTrace();
    }

run above code, will give you:

-10

Upvotes: 1

Steven De Groote
Steven De Groote

Reputation: 2233

Why don't you check out the source code of some existing calculators? Perhaps those will will you gather some ideas about what is a good approach.

One example I found on sourceforge which I looked through previously is this:

http://sourceforge.net/projects/jcalcadvance/

Upvotes: 1

Related Questions