The problem is most likely that you use == to compare words, and Java by == links are compared, use sc.nextLine().equals("Stop")
Here is a fully working code
Scanner sc = new Scanner(System.in); String[] words1 = new String[25]; for (int i = 0; i < 25 && sc.hasNextLine(); i++) { String nextLine = sc.nextLine(); if (nextLine.equalsIgnoreCase("stop")) { break; } words1[i] = nextLine; } for (String aWords1 : words1) { System.out.print(aWords1 + " "); }
The first problem you had was that you did the iterations, even though the lines were already gone. Corrected by adding && sc.hasNextLine() .
The second problem was that you wrote this
if (sc.nextLine().equals("Stop")) { System.exit(0); } else{ words1[i]=sc.nextLine();
You called nextLine , the first time the line was, and the second time it did not, because the nextLine does not always return the same value in one iteration, this is not an idempotent method.
Well, another problem was that you called System.exit(0) , if you met the word stop , and this completes jvm execution, and you would never get to a loop that displays the values ​​of the array
Additionally. Scanner cannot call the close method when you pass it System.in , because it closes the stream that was passed to it and so you can accidentally close System.in , and then look for an error for a long time
break;) - default locale