mardi 15 septembre 2020

"While loop" doesn't work, while "if loop" does [duplicate]

So I have a piece of code that uses a while statement that doesn't work. I changed it to use an if statement that did end up working. Can anyone explain to me why the if statement worked, while the while statement didn't? Any help is much appreciated.


class Main {

    static String myCharacterName = "JIMMY";


    public static void main(String[] args){
    
    String resp = "ksdfkdsa";
    
    while (resp != "YES") {
      System.out.println("are we there yet?   (respond here with something and then hit the Enter key): ");
      
      Scanner input = new Scanner(System.in);
      
      resp = input.nextLine();
      System.out.println(resp);
      }


    }

}

import java.util.Scanner;

class Main {

    static String myCharacterName = "JIMMY";

    
    public static void main(String[] args){
    
    String resp = "ksdfkdsa";
    
    System.out.println("are we there yet?   (respond here with something and then hit the Enter key): ");
    
      Scanner input = new Scanner(System.in);
      
    
      resp = input.nextLine();
      System.out.println(resp);
    
    if (resp.equals("YES")) {
      System.exit(0);
    }
    else {
      System.out.println("are we there yet?   (respond here with something and then hit the Enter key): ");
      
    
      resp = input.nextLine();
      System.out.println(resp);
    }    
    }

}

Aucun commentaire:

Enregistrer un commentaire