jeudi 23 juin 2016

Works with integers but not strings [duplicate]

This question already has an answer here:

I am just starting to learn Java and I have tried to make a simple password program, my question is why does the first program not work but the second one does? I can't figure out what is going wrong. To me the only difference is that the first program uses strings and the second integers, yet one works and the other doesn't. The difference in the code is that I have made the variables in the first strings and in the second integers, I also change nextLine() to nextInt().

import java.util.Scanner;
public class Password {
public static void main(String[] args) {
    Scanner brick = new Scanner(System.in);
    String Attempt, Password;
    Password = "k";
    System.out.println("Enter your password ");
    Attempt= brick.nextLine();
    int Lock = 0;

    while (Lock == 0) {
    if (Attempt == Password) {
        System.out.println("ok");
        Lock++;
    }else{
        System.out.println("Password is incorrect, try again: ");
        Attempt= brick.nextLine();
    }
    }
    brick.close();
}
}

Second Program:

import java.util.Scanner;
public class Password {
public static void main(String[] args) {
    Scanner brick = new Scanner(System.in);
    int Attempt, Password;
    Password = 1;
    System.out.println("Enter your password ");
    Attempt= brick.nextInt();
    int Lock = 0;

    while (Lock == 0) {
    if (Attempt == Password) {
        System.out.println("ok");
        Lock++;
    }else{
        System.out.println("Password is incorrect, try again: ");
        Attempt= brick.nextInt();
    }
    }
    brick.close();
}
}

Aucun commentaire:

Enregistrer un commentaire