Need help let's say there is an array:

String[] s = {"26", "8", "15", "12", "11", "12"}; 

It is necessary to do so if we are looking for "12", as a result, it was entered into one variable:

 String a = "1212"; 

and if the string "12" is not in the array, then

 String a = "0"; 

I wrote the following code but it does not work correctly:

  String[] s = {"26", "8", "15", "12", "11", "12"}; for (int i = 0; i < s.length; i++) { if (s[i].equals("12")) { d += s[i]; System.out.println(d); } else { d = "0"; } } System.out.println(d); 
  • What does it mean wrong? .. The program does not compile, drops or the output does not meet expectations? .. You, by the way, would have to i++ instead of ++i in the first cycle
  • Thank. The output does not match. - Binary
  • When you reach 11, reset your string. As a result, its value is "012" - YuriySPb
  • I understand this I do not understand how to fix - Binary

1 answer 1

Alternatively, you can check the string for emptiness.

 String d = ""; String[] s = {"26", "8", "15", "12", "11", "12"}; for (int i = 0; i < s.length; i++) { if (s[i].equals("12")) { d += s[i]; } } if(d.isEmpty()) d = "0"; System.out.println(d);