Search code examples
javaandroidandroid-studiocalculatorcalculation

Converting string into int to find a result in java android


how to convert some character like this +,-,/,*, from String into an int, i try to find some result using int, but this character +,-,/,* make it error, when i am trying to convert from String into int,

normally when you type int i = 12+12 it will display the result of 24, but when i am trying to convert it from String to int, my app force close, any advice?, thank you


Solution

  • Instead of Integer.parseInt(getTextView); , you will have to first extract the numbers from the string obtained from the TextView and then convert them to integer separately and then do the arithmetic operation.

    Do it as below.

    equal.setOnClickListener(new View.OnClickListener() {
        @Override             
        public void onClick(View v) {
            String getTextView = textView.getText().toString();
            String[] numbers = getTextView.split("+");
            int value = Integer.parseInt(numbers[0]) + Integer.parseInt(numbers[1]);
            textView.setText(value);  
        }
    }
    

    UPDATE Replace

    String[] numbers = getTextView.split("+");
    

    With

    String[] numbers = getTextView.split("\\+");
    

    to prevent the dangling metacharacter error.