Skip to content
Advertisement

how do I make while loop run until a certain input is placed?

the idea is basically the loop takes in input and it runs until I type “quit” but it doesn’t work the way I want to and I can’t figure out why 🙁 (p.s. im a beginner that came from python pls be kind)

import java.util.Scanner;
class HelloWorld {
    static String s1;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        do {
            s1 = in.next();
        } while (s1 != "quit");

        System.out.println(s1);
    }
}

I also tried adding a temporary variable so that the while loop could check the condition before continuing but it doesn’t work that way too…

import java.util.Scanner;
class HelloWorld {
    static String s1;
    static String s2;
    static int s3;
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        do {
            s1=in.next();
            if (s1=="quit"){
                break;
            }
            s2=in.next();
            s3=in.nextInt();
        
        } while (s1!="quit");
        System.out.println("Terminate");
        
    }
}

Advertisement

Answer

Your code works fine, You just cannot use == operator to compare Strings. Use equals() or equalsIgnoreCase() method instead.

   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        do {
            s1 = in.next();
        } while (!"quit".equals(s1)); // use equals

        System.out.println(s1);
    }

If You are comparing by == You are checking if both sides reference to same object. When You are using equals(), You are comparing the String values. So even if You have multiple objects with value “quit”, == will return false, but equals() will return true.

You can read more here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement