lundi 30 novembre 2015

Java: while loop not working

I want to check the users input when a new game is created, and see if it is y, n, or neither.

For some reason it skips the while loop all together and just outputs "Welcome to Questions."

edit: I changed the = to == but now it just says invalid input no matter what the input is

import java.util.Scanner;

public class Questions {

public static final Scanner INPUT = new Scanner(System.in);

private boolean ans;


public Questions() {

  while (ans = false) {
      System.out.print("Do you want to start a new game (y/n)?: ");
      String input = INPUT.nextLine();

      if (input == "y"){
          ans = true;
          //some code
      }

      else if (input == "n"){
          ans = true;
          //some code
      }

      else {
          System.out.println("Invalid input, Try again");
          ans = false;
      }

  }//end while

}

public static void main(String[] args) {
  Questions game = new Questions();
  System.out.println("Welcome to Questions.");

}

Aucun commentaire:

Enregistrer un commentaire