-2

I have an array named questions array for String type that stores in the questions. I want to convert the questionArray[0] to an int. I have used the following statement to do that.

int aa = Integer.parseInt(questionArray[0]);

But when I implement this statement and when I run the application I get an error saying : invalid int: "10-4". Note that the 10-4 can be any random arithmetic expression because its a random questions game. e.g.: 9+1, 10/5 etc.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Harsh
  • 187
  • 2
  • 2
  • 7
  • If I understood correctly questionArray[0] equals to "10-4" which is a string with characters that are not numbers, here the '-' character. ParseInt can only handle numbers, not expressions if I remember correctly. You would have to write a function that extracts the fist and second numbers from the string and then do the math according to the operator in between – TheEdgeOfRage Feb 13 '16 at 12:20
  • I deleted my answer and now I am working on the new one. Hold tight – Faraz Feb 13 '16 at 12:26
  • 1
    why does this question have such a low score? it follows all the rules for asking a good question and it is pretty obvious what the problem is..? guys, don't just down vote, leave at least a comment..! – Neuron Feb 13 '16 at 12:38

2 Answers2

4

"10-4" is not a simple integer, it's a calculation, so parsing it to an int will yield no results..

You'll have to parse your string..

int aa = evaluteQuestion(questionArray[0]);

And the actual magic happens here:

public static int evaluteQuestion(String question) {
    Scanner sc = new Scanner(question);

    // get the next number from the scanner
    int firstValue = Integer.parseInt(sc.findInLine("[0-9]*"));

    // get everything which follows and is not a number (might contain white spaces)
    String operator = sc.findInLine("[^0-9]*").trim();
    int secondValue = Integer.parseInt(sc.findInLine("[0-9]*"));
    switch (operator){
        case "+":
            return firstValue + secondValue;
        case "-":
            return firstValue - secondValue;
        case "/":
            return firstValue / secondValue;
        case "*":
            return firstValue * secondValue;
        case "%":
            return firstValue % secondValue;
        // todo: add additional operators as needed..
        default:
            throw new RuntimeException("unknown operator: "+operator);
    }
}

If you have more parts in your expressions, you might want to put the code above into a loop. watch out for order of operation though. Things might get a little hairy if you want to implement a proper parser for any expression

Neuron
  • 5,141
  • 5
  • 38
  • 59
  • 1
    You need to make `int result = 0;`. Else, the compiler will show an error. – dryairship Feb 13 '16 at 12:56
  • there you go, fixed it ;) – Neuron Feb 13 '16 at 12:57
  • @Hackerdarshi No, that isn't necessary, since the program won't reach `return result` before it is initialized. The fix is still worth, since it is better code now, imho. – Tom Feb 13 '16 at 13:30
  • 1
    @Tom no, he is right. Initially I didn't have a default case. But the variable is obsolete by now anyways.. – Neuron Feb 13 '16 at 13:33
  • Ah, ok. Missed that his comment is older than the edit with the `default` case :). – Tom Feb 13 '16 at 13:35
  • Its all fine now. But now, I was thinking of how to add things like: `7²` and `2³`. – dryairship Feb 13 '16 at 13:36
  • @Hackerdarshi feel free to edit my post ;) – Neuron Feb 13 '16 at 13:38
  • what about being a little strict for once and only accept `7^2`? or maybe there is a nice way of converting `²` to `^2` (I know there is some built in thing for doing `é`->`´e`, but I am too lazy to look it up..)? – Neuron Feb 13 '16 at 13:42
0

It is a bit complicated than just parsing a String because it has a arithmetic sign and it can be anything. So, lets go over it step by step:

//Lets say you have a string like this
questionArray[0] = "10+4";
//Lets find the Arithmetic sign first in the String
String sign = null;

Pattern regex = Pattern.compile("[+*/]|(?<=\\s)-");
Matcher matcher = regex.matcher(questionArray[0]);
    while(matcher.find()) {
       sign = matcher.group().trim();  //Store that Arithmetic sign here.       
    }

String [] parts = questionArray[0].split("[+*/]|(?<=\\s)-"); //Now break up the string using this regex. 
                                              //This regex will find whatever Arithmetic sign 
                                              //there is inside this String and store the result 
                                              //in parts array.

int firstNumber = Integer.parseInt(parts[0]); //The first number in the String
int secondNumber = Integer.parseInt(parts[1]);//The second number in the String

//a simple if-else statements that will help us find the final answer.
int result = 0;
if (sign.equals("+")){
    result = firstNumber + secondNumber;
} else if (sign.equals("-")) {
    result = firstNumber - secondNumber;
} else if(sign.equals("*")) {    
    result = firstNumber * secondNumber;
} else if (sign.equals("/")){
    result = firstNumber / secondNumber;
} else {
    System.out.println("unknown operation");
}

System.out.println(result);
Faraz
  • 6,025
  • 5
  • 31
  • 88
  • @FarazDurrani what if its /,* or + ? – Harsh Feb 13 '16 at 12:25
  • @Faraz Durrani no need to get rude! +you have 4 `if` conditions, which are exclusive to one another. yet all 4 get executed. maybe your code would benefit of some `else if`s. or maybe even a `switch case`? – Neuron Feb 13 '16 at 13:02
  • 1
    @FarazDurrani: I _still_ haven't downvoted, so there's nothing I could take back. – Marvin Feb 13 '16 at 13:25