Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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");
        
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading