mardi 5 mars 2019

Java While loop doesn't end

As said in the title, the while loop for my code doesn't end. It's supposed to end when String Code is equal to the user input, yet it doesn't.

import java.util.Scanner;
import java.util.Random;
public class Mastermind {   
    public static void playMastermind() {
      Scanner user;
      String Code;
      Random code;
      int x;
      String s;
      code = new Random();
      Code = String.format("%04d", code.nextInt(10000));
      user = new Scanner(System.in);
      char c1 = Code.charAt(0);
      char c2 = Code.charAt(1);
      char c3 = Code.charAt(2);
      char c4 = Code.charAt(3);
      x = 0;
      System.out.println("Welcome to Mastermind");
      System.out.println(Code);
      System.out.print("Enter your guess: ");
      while ((s = user.next()) != Code) {
        char u1 = s.charAt(0);
        char u2 = s.charAt(1);
        char u3 = s.charAt(2);
        char u4 = s.charAt(3);
        if (c1 == u1) {
          x++;
        }
        if (c2 == u2) {
          x++;
        }
        if (c3 == u3) {
          x++;
        }
        if (c4 == u4) {
          x++;
        }
        System.out.println("You have " + x + " correct!");
        x = 0;
        System.out.print("Enter your guess: ");
      }
      System.out.println("You guessed it!");
    }
}

I have also tried having the user input in the actual while loop instead of in the while loop header, but that had the same results. Everything else in the code works except it, and I have no idea why. So why doesn't the code complete when the while statement is false?




Aucun commentaire:

Enregistrer un commentaire