Problem with the while loop in JAva

1

I try to execute a very simple code, I simply want the program to ask the user to enter their hobbies until the user enters 'done'. Then, the program goes to the next part. The problem appears when I enter 'done' but the loop continues.

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

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String>  arrayList1 = new ArrayList<String();
        String hobbies = " ";
        while (hobbies != "done"){
            System.out.println("Enter your hobbies: ");
            hobbies = scanner.nextLine();
            arrayList1.add(hobbies);
        }

        for (int i = 0; i<arrayList1.size();i++){
            System.out.println("Hobby #"+(i+1)+" : " + arrayList1.get(i));
        }
    }
}
    
asked by nerviosus 17.07.2018 в 18:32
source

2 answers

2

When comparing String it is advisable to use .equals() since when using !=, == the reference is compared, basically if it is the same object or not.

Here the change:

public class Main
{
    public static void main(String[] args)
    {
    Scanner scanner = new Scanner(System.in);
    ArrayList<String> arrayList1 = new ArrayList<String>();
    String hobbies = " ";

    while (!hobbies.equals("done"))
    {
        System.out.println("Enter your hobbies: ");
        hobbies = scanner.nextLine();
        arrayList1.add(hobbies);
    }

    for (int i = 0; i < arrayList1.size(); i++)
    {
        System.out.println("Hobby #" + (i + 1) + " : " + arrayList1.get(i));
     }
   }
}

Greetings.

    
answered by 17.07.2018 / 18:56
source
1

look with this loop, so you always run a first time and the comparison of strings should be with equals

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String>  arrayList1 = new ArrayList<String>();
        String hobbies = " ";
        do{
            System.out.println("Enter your hobbies: ");
            hobbies = scanner.nextLine();
            arrayList1.add(hobbies);
        }while (!hobbies.equals("done");

    for (int i = 0; i<arrayList1.size();i++){
        System.out.println("Hobby #"+(i+1)+" : " + arrayList1.get(i));
    }
}

}

try this and tell me, I hope it serves you and mark it as valid By: JJ

    
answered by 17.07.2018 в 19:09