This Java program simulates a simple login system. It prompts the user for a username and password, checks these credentials against predefined values, and then displays whether the login is successful or not. The program utilizes a static method to perform the validation and uses the Scanner class to read input from the user.
import java.util.Scanner;
public class LoginExample {
static boolean checkUserInput(String username, String password) {
String pw = "123456", name = "user";
if (username.equals(name) && password.equals(pw)) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String username, password;
System.out.println("Enter username: ");
username = scan.next().toLowerCase();
System.out.println("Enter password: ");
password = scan.next().toLowerCase();
if (checkUserInput(username, password)) {
System.out.print("Successfully logged in");
} else {
System.out.print("Wrong username or password");
}
}
}
Enter username:
user
Enter password:
123456
Successfully logged in
Enter username:
jason
Enter password:
3453
Wrong username or password
static boolean checkUserInput(String username, String password) {
String pw = "123456", name = "user";
if (username.equals(name) && password.equals(pw)) {
return true;
} else {
return false;
}
}
static boolean checkUserInput(String username, String password) {
String pw = "123456", name = "user";
if (username.equals(name) && password.equals(pw)) {
return true;
} else {
return false;
}
}
The checkUserInput method validates the provided username and password against predefined values.
username (String): The username entered by the user.password (String): The password entered by the user.pw and name with predefined values "123456" and "user", respectively.username equals name and password equals pw using the equals method.true if both conditions are met; otherwise, return false.public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String username, password;
System.out.println("Enter username: ");
username = scan.next().toLowerCase();
System.out.println("Enter password: ");
password = scan.next().toLowerCase();
if (checkUserInput(username, password)) {
System.out.print("Successfully logged in");
} else {
System.out.print("Wrong username or password");
}
}
The main method is the entry point of the program. It reads the username and password from the user, calls the checkUserInput method to validate the credentials, and displays the login result.
Scanner object to read input from the console.username and password to store the user’s input.next method, converting it to lowercase.next method, converting it to lowercase.checkUserInput method with username and password as arguments.true; otherwise, print “Wrong username or password”.