-3

I'm a beginner in coding and would appreciate any feedback. This code seemed easy but I'm not sure why the "STOP" exit condition isn't being fulfilled. Code:

    ```
import java.util.Scanner;
import java.util.ArrayList;

public class U7_L2_Activity_One{

  public static void main(String[] args){
    System.out.println("Please enter words, enter STOP to stop the loop.");
Scanner scan=new Scanner(System.in);
 ArrayList<String> list=new ArrayList<String>();
 String x;


while(true){
 x = scan.nextLine();
 if (x =  = "STOP")
 {
   System.out.println(list);
   for (int i = 0; i <= list.size()- 1; i++){
     System.out.println(list.get(i));
   }
   System.exit(0);

}
else{
  list.add(x);}
}

} }

1 Answers1

0

So basically you want your program to end if the variable X is equal to the word "STOP" right? So in that case you need to change de comparison inside if. In java you can't compare strings using the operator ==. When you do that you're comparing if the objects reference are equal.

Solution: To compare Strings you can use YourVariable.equals(SomeString). In your case just change x=="STOP" to x.equals("STOP")

For reference:
Strings Method Equals: https://www.w3schools.com/java/ref_string_equals.asp

Irocha
  • 56
  • 3