The following code is available:

package com.company; public class Main { public static void main(String[] args) { String[] arr = {"+5", "-3"}; int a = 0; for (int i = 0; i<arr.length; i++){ if (arr[i].contains("+")){ arr[i].replace('+',' '); } else if (arr[i].contains("-")){ arr[i].replace('-',' '); } System.out.print(arr[i]+" "); } } } 

The task of the program is the removal of the element of the array, the definition of the sign for the calculation and the subsequent calculation. a is the initial number. I did not find another way to remove +/-, after determining the sign, but this one does not work either. Where is the mistake?

    3 answers 3

    It does not work, because strings are immutable . You are trying to replace + with a space in the arr[i] line, but it will not be replaced, instead, the replace method will return a new line to you, in which + will be replaced with a space. Accordingly, for the code to work, you need to write like this:

     arr[i] = arr[i].replace('+',' '); 

      I propose such a solution, given that a with type int, i.e. not fractional, the result will be truncated:

       public class Test { public static void main(String[] args) { String[] arr = {"+5", "-3", "*5", "/2", "%2"}; int a = 0; for (int i = 0; i<arr.length; i++){ // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠΌ Π·Π½Π°ΠΊ ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ char sign = arr[i].toCharArray()[0]; // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠΌ число, ΠΈ ΠΏΡ€ΠΎΠΈΠ·Π²Π΅Π΄Ρ‘ΠΌ автораспаковку Π² ΠΏΡ€ΠΈΠΌΠΈΡ‚ΠΈΠ² int int num = Integer.valueOf(arr[i].substring(1)); // условия для Π·Π½Π°ΠΊΠ° ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ switch(sign){ case '+' : a += num; break; case '-' : a -= num; break; case '*' : a *= num; break; case '/' : a /= num; break; case '%' : a %= num; break; } } // Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ System.out.print(String.format("Result: %d", a)); } } 

      enter image description here

        Since you specify numbers by strings, you can convert them with built-in tools:

         public static void main(String[] args) { String[] arr = {"+5", "-3"}; int result = 0; for (String numStr : arr) { result += Integer.parseInt(numStr); } System.out.println(result); }