0

Hi there so i am new to java and am learning it, so i put together this little script, so i was wondering why it dosent work:

public class Main {

    public static void main(String[] args) {
        String text;

        try (Scanner input = new Scanner(System.in)) {

            System.out.println("Input");

            text = input.nextLine();

            while (text == "sampleText") {
                System.out.println("outputText");
            }
        }
        System.out.println("Your input " + text);

    }
}
fuggerjaki61
  • 822
  • 1
  • 11
  • 24
HmonsterG
  • 3
  • 1
  • Also note that if you were to do the comparison correctly, you'll have an infinite loop, since you do not update the value of `text` in your loop. – azurefrog Feb 28 '20 at 19:48
  • 1
    Welcome to stack overflow! A small word of advice when asking questions -- please be specific when you say something doesn't work, it helps the community narrow down solutions for you. – Sterling Archer Feb 28 '20 at 19:50
  • the string comparator is one problem. But then once you correct that your code will go into an infinite (while) loop. You should put `while(true) {` above System.out.println("Input") and the close bracket before the close bracket for your try loop – ControlAltDel Feb 28 '20 at 19:50
  • just replace while(text == "Yeet") with if(text.equals("Yeet")) – CausingUnderflowsEverywhere Feb 28 '20 at 19:51
  • @ControlAltDel `while(true)`? He would still have an infinite loop then, this probably would work best as a `do-while` loop. – Nexevis Feb 28 '20 at 19:51
  • Wow thank you so much for the quick corrections! Fixed now! – HmonsterG Feb 28 '20 at 19:57
  • @Nexevis i haven't learnt those yet, but they seem useful so im going to go learn them! – HmonsterG Feb 28 '20 at 19:58
  • @HmonsterG Honestly their main use is with something like `Scanner`, I rarely have ever needed to use a `do-while` in a real project at least from my perspective. The main advantage is that it will _always_ run at least one time, where a `while` or `for` might not run even a single time. – Nexevis Feb 28 '20 at 19:59

0 Answers0