My code for linked lists practice doesn't want to work | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

My code for linked lists practice doesn't want to work

So I'm getting the error Java.Util.NoSuchElementException. even though I'm adding the word to the words linkedlists, it thinks theres nothing in that position. Here is the code, can someone tell me what the problem is import java.util.LinkedList; import java.util.Scanner; public class Main { public static void main(String[ ] args) { Scanner scanner = new Scanner(System.in); LinkedList<String> words = new LinkedList<String>(); while(words.size()<5) { String word = scanner.nextLine(); //add the word to LinkedList if(word.length()>4) { words.add(word); } } System.out.println(words); } }

30th Apr 2021, 5:04 PM
Serana Zentha
Serana Zentha - avatar
5 Answers
+ 3
In your code, the java.util.NoSuchElementException is being thrown because you're trying to take input when there is no more input to take. The problem is not with your code, as I ran the code with correct input and it worked fine. Make sure you're giving the correct input. According to your code, there should be atleast 5 inputs of length > 4. Example input """ hello hlelo holle holel java hlloe """ (6 inputs out of which atleast 5 are of length greater than 4)
30th Apr 2021, 6:03 PM
XXX
XXX - avatar
+ 1
You should use length() outside the while loop instead. Perhaps, it may help: import java.util.LinkedList; import java.util.Scanner; public class Test { public static void main(String[ ] args) { Scanner scanner = new Scanner(System.in); LinkedList<String> words = new LinkedList<>(); while(words.size()<5){ String word = scanner.nextLine(); words.add(word); } for(String s: words) { if(s.length() > 4) { System.out.println(s); } } } }
21st Sep 2021, 1:09 PM
Ammar Andiko
Ammar Andiko - avatar
0
XXX the thing is, ot foes not give me the option to put input. For the practice question in the lesson exceptions lists and threads, it puts in the input, but for some reason I'm getting this error
30th Apr 2021, 6:10 PM
Serana Zentha
Serana Zentha - avatar
0
XXX nvm I fixed it thx
30th Apr 2021, 6:17 PM
Serana Zentha
Serana Zentha - avatar
0
Serana Zentha I can't tell much without seeing the question. Can you link the question here (or tell its name)? If it is a pro-only question, I'll need the description also as I am not a pro user. EDIT: Ok you fixed it
30th Apr 2021, 6:18 PM
XXX
XXX - avatar