0

whats wrong with this code?

import java.util.*; import java.io.* ; class Main { public static void main(String[] args) { List<String> sList = new ArrayList<String>() ; Scanner sc = new Scanner(System.in) ; for(int i = 1 ; i <= 5; i++){ String a = sc.nextLine() ; for(String b : sList) if(a.equalsIgnoreCase(b)){ break; System.out.println("This strig already exists in the list!");<-----i get error here, it says out of reach } else{ sList.add(a); } } } }

19th Sep 2022, 7:03 PM
Lenoname
5 odpowiedzi
+ 1
Yes. break; causes loop stop there itself. So next statements skipped. So your logic, there is no chance of print statement in any way.. First print statement.. Then add break statement. Swap 2 statements... edit: if(a.equalsIgnoreCase(b)) { System.out.println("This string already exists in the list!"); break; }
19th Sep 2022, 7:21 PM
Jayakrishna 🇮🇳
+ 1
this code is still not working. No errors but when i write a string 2 times i dont get "this string already exists!" import java.util.*; class Main { public static void main(String[] args) { List<String> sList = new ArrayList<String>() ; Scanner sc = new Scanner(System.in) ; System.out.println("Write 5 strings!"); for(int i = 1 ; i <= 5; i++){ String a = sc.nextLine() ; for(String b : sList){ if(a.equalsIgnoreCase(b)){ System.out.println("This string already exists in the list!"); break ; } else{ sList.add(a); } } } } }
20th Sep 2022, 9:07 AM
Lenoname
+ 1
The suggestion only works for removing error.. Because you are not posted your full task.. Your code will add input into list of list size times, if it is not in list.. and list goes on increasing to infinite loop. On only first item match, will break by showing message.. I think, I already posted, by some corrections, which accept 5 inputs, only distinct values are added to list.. You can check now... https://www.sololearn.com/discuss/3085140/?ref=app
20th Sep 2022, 10:35 AM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 its the whole task, the user must write 5 strings which will be put in a list, if any string already exists in the list of strings the program will tell the user "the string already exists!" Otherwise add it to the list. At the end of the program all of the strings in the list will be printed out.
20th Sep 2022, 8:16 PM
Lenoname
0
The code I posted adds the strings to list. Leter you can print by for( String s : sList) System.out.println( s );
20th Sep 2022, 8:45 PM
Jayakrishna 🇮🇳