-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.

Harsh
  • 177
  • 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 - Freedom for Ukraine 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

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
  • 5,467
  • 5
  • 22
  • 73