I'm trying to make a game where you have to login with certain credentials and after that the user is given a choice between 2 games. I am able to code the games but am stuck at making the input for choice between games. Any help is appreciated! (It's the very last line that seems to not work, I have no idea why).
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SkillsDemo3 {
boolean again = true;
int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password) {
this.username = username;
this.password = password;
}
String GetUsername() { return username; }
String GetPassword() { return password; }
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers) {
if (user.GetUsername().equals(username)) {
if (user.GetPassword().equals(password)) {
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null) {
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
} else {
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
boolean again = true;
int action = 0;
if (action == 1) {
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
} else if (action == 2) {
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
SkillsDemo3 what = new SkillsDemo3();
while (what.again) {
System.out.println("Please type 0 to continue or 1 to stop :");
what.action = Integer.parseInt(br.readLine());
System.out.println("You typed : "+what.action);
what.SkillsDemo3();
}
}
}
You don't need an object of your class SkillsDemo3
Just make the variables action and again static and get your workflow right. I tried to implement some workflow but i don't know if this fits for you.
public class SkillsDemo3 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
System.out.println("Please type 0 to continue or 1 to stop :");
action = Integer.parseInt(br.readLine());
again = action == 0;
System.out.println("You typed : "+action);
}
}
}
Related
I am trying to add a User into a LinkedList using Java, but I am wondering if there is a shorter way to check if multiple strings are empty instead of using if statements everytime I input a new string
This is the method I came up with
public void addUser() {
int error = 0;
do {
Users user = new Users();
String name = JOptionPane.showInputDialog(null, "Enter your name");
if (name.isEmpty()) {
error = 1;
} else {
String password = JOptionPane.showInputDialog(null, "Enter a password");
if (password.isEmpty()) {
error = 1;
} else {
// more string inputs
}
}
} while (error != 0);
}
Implement a separate method to read the input data until a valid string is provided and call this method with custom prompt:
private static String readInput(String prompt) {
String input;
do {
input = JOptionPane.showInputDialog(null, prompt);
} while (input == null || input.isEmpty());
}
public void addUser() {
String name = readInput("Enter your name");
String password = readInput("Enter a password");
// ...
User user = new User(name, password, ...);
// ...
}
I'm trying to code a simple login system with authentication.
I first try to give user two choices of login or registering.
Then if user chose to register, and the information will be stored in the .txt file to then used to compare with the login details to check whether this user existed or password is valid.
I encountered a problem which is that when I registered two or more 'accounts',
I'm able to login the other accounts other than the first account.
It seems like something is missing in term of 'reading' through the .txt file, finding the data.
public static void main(String[] args) throws Exception {
File file = new File("database.txt");
PrintWriter output = new PrintWriter(new FileWriter(file, true));
Scanner input = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
Customers customer = new Customers();
System.out.println("1. Login");
System.out.println("2. Register");
int option = keyboard.nextInt();
switch (option) {
case 1:
System.out.println("LOGIN PAGE");
System.out.println("Username: ");
String inpUser = keyboard.next();
if (input.next().equals(inpUser)) {
System.out.println("Password: ");
String inpPass = keyboard.next();
if (input.next().equals(inpPass)) {
System.out.println("Login Succesful!");
} else {
System.out.println("Password is incorrect.");
}
} else {
System.out.println("Username is incorrect.");
}
break;
case 2:
System.out.println("REGISTRATION PAGE");
System.out.println("Username: ");
String username = keyboard.next();
customer.setUsername(username);
System.out.println("Password: ");
String password = keyboard.next();
customer.setPassword(password);
System.out.println("You've successfully registered! You may login now.");
output.println(customer.getUsername());
output.println(customer.getPassword());
output.close();
break;
default:
System.out.println("1 OR 2 PLEASE");
}
keyboard.close();
input.close();
}
Customers code
public Customers(){
}
public Customers(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
You're only checking if the user input is equal to the first row in your .txt file.
if (input.next().equals(inpUser)){
You need to check every entry. To do so you need to iterate over every row in your file. Something like this should do it.
case 1:
System.out.println("LOGIN PAGE");
System.out.println("Username: ");
String inpUser = keyboard.next();
boolean found = false;
while(input.hasNext() && !found) { // Add a loop here to chek for every entry in the file
if (input.next().equals(inpUser)){
System.out.println("Password: ");
String inpPass = keyboard.next();
if (input.next().equals(inpPass)){
System.out.println("Login Succesful!");
found = true;
break;
}
}
}
if(!found) {
System.out.println("Login incorrect!");
}
I want to match the username "carl" to the password "0001", as well as the other elements, but it's not working. Can anyone explain me how to match each elements of "username" to the elements of "password"? Thank you very much!
This is my code:
class log{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String [] username ={"carl", "may", "joseph", "oliver", "ashley"};
String []password={"0001", "0002", "0003", "0004", "0005"};
public void login() throws IOException{
System.out.print("\nUSERNAME: ");
uname=br.readLine();
System.out.print("PASSWORD: ");
pword=br.readLine();
for (j = 0; j <= 4; j++) {
if (username[j].equals(password[j])) {
uname=username[j];
pword=password[j];
}
}
while((!uname.equals(password[j]))&&(!pword.equals(username[j]))){
System.out.println("Invalid username/password.");
System.out.print("\nUSERNAME: ");
uname=br.readLine();
System.out.print("PASSWORD: ");
pword=br.readLine();
}
public void main(String[] args)throws IOException {
log b=new log();
b.login();
}
You can use OOP (Object Oriented Programming) to make it easier in sovling your problem:
Here is my sample solution:
User class:
class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
User user2 = (User) o;
if (this.username.equals(user2.getUsername()) && this.password.equals(user2.getPassword()))
return true;
return false;
}
}
Login class:
public class Login {
private User[] users = new User[]{
new User("carl", "0001"),
new User("may", "0002"),
new User("joseph", "0003"),
new User("oliver", "0004"),
new User("ashley", "0005"),
};
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nUSERNAME: ");
String uname = br.readLine();
System.out.print("PASSWORD: ");
String pword = br.readLine();
boolean success = new Login().login(new User(uname, pword));
if (success)
System.out.println("The user account is valid, login");
else
System.out.println("The username and/or password is invalid.");
}
public boolean login(User user) {
for (int i = 0; i < users.length; i++) {
if (users[i].equals(user))
return true;
}
return false;
}
}
I think you should modify your method in following way
public void login() throws IOException {
System.out.print("\nUSERNAME: ");
uname = br.readLine();
System.out.print("PASSWORD: ");
pword = br.readLine();
while (!isValid(uname, pword)) {
System.out.println("Invalid username/password.");
System.out.print("\nUSERNAME: ");
uname = br.readLine();
System.out.print("PASSWORD: ");
pword = br.readLine();
}
}
//checks if the entered username and password are correct
public boolean isValid(String uname, String pword) {
for (int j = 0; j <username.length; j++) {
if (username[j].equals(uname)) {
if (!password[j].equals(pword))
return false;
else
return true;
}
}
return false;
}
I think it it better when you work with an extra Class User.
The class looks like this:
class User {
private String name;
private String pw;
public User (String name, String pw) {
this.name = name;
this.pw = pw;
}
public String getName() {
return this.name;
}
public String getPw() {
return this.pw;
}
}
In your program logic you have a list with all users:
ArrayList<User> userList
Now you have change the login algorithm:
class log{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
ArrayList<User> userList = ...; //Here you have to add all users first
boolean loginCheck = false;
while(loginCheck == false) {
System.out.print("\nUSERNAME: ");
uname = br.readLine();
System.out.print("PASSWORD: ");
pword = br.readLine();
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getName.equals(uname) && userList.get(i).getPw.equals(pword)) {
loginCheck = true;
break;
}
}
}
}
public void main(String[] args)throws IOException {
log b=new log();
b.login();
}
You can make the algorithm faster if you change the check for the user input into this:
for (int i = 0; i < userList.size(); i++) {
if (userList.get(i).getName.equals(uname)) {
if (userList.get(i).getPw.equals(pword)) {
loginCheck = true;
break;
} else {
break;
}
}
}
In my application user has to enter in the console name, username and password. Later the program should check the login to the involvement of a dynamic array, and if not it there, add it, and if it is, display an error warning.
When you run, an input box, where quietly entered above "name", "username" and "password". However, the program does not make login check for involvement in the array and displays an error message, as well, it does not take themselves array field.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class User {
public static void main(String[] args) throws IOException {
BufferedReader bReader =new BufferedReader(new InputStreamReader(System.in));
String name = bReader.readLine();
String login = bReader.readLine();
String password = bReader.readLine();
UserADD(name,login,password);
}
public static ArrayList<String> UserADD(String name,String login,String password) {
ArrayList <String> users = new ArrayList<String>();
for (int i = 0; i<users.size(); i++) {
if (users.contains(login)) {
System.out.println("Это имя пользователя уже занято");
}
else users.add(name);
users.add(login);
users.add(password);
System.out.println(users);
}
return users;
}
}
Your ArrayList<String> users is method local. This means that every time you call the method another object gets created and it's initially empty.
The possible solution would be to create an ArrayList in main method and pass it as an argument to userAdd().
As you are learning Java please try to follow best practices. Don't start function names with a capital letter. They're reserved for class names.
ArrayList users is local under UserADD method.
Declare ArrayList users as global will fix the problem.
public class User {
//Global declaration of ArrayList users
public static ArrayList <String> users = new ArrayList<String>();
public static void main(String[] args) throws IOException {
BufferedReader bReader =new BufferedReader(new InputStreamReader(System.in));
String name = bReader.readLine();
String login = bReader.readLine();
String password = bReader.readLine();
UserADD(name,login,password);
}
public static ArrayList<String> UserADD(String name,String login,String password) {
//don't initialize users ArrayList here
for (int i = 0; i<users.size(); i++) {
if (users.contains(login)) {
System.out.println("Это имя пользователя уже занято");
}
else users.add(name); users.add (login);users.add(password);
System.out.println(users);
}
return users;
}
}
You have to hold the users in a class object to live longer than the function call. A bit like:
public class UserRegistration {
private List<String> users = new ArrayList<>();
public static void main(String[] args) throws IOException {
new UserRegistration().run();
}
private void run() {
BufferedReader bReader =new BufferedReader(new InputStreamReader(System.in));
String name = bReader.readLine();
String login = bReader.readLine();
String password = bReader.readLine();
addUser(name,login,password);
}
public boolean addUser(String name,String login,String password) {
for (int i = 0; i<users.size(); i++) {
if (users.contains("\t" + login + "\t")) {
System.out.println("Это имя пользователя уже занято");
return false;
}
}
users.add(name + "\t" + login + "\t" + password);
return true;
}
}
The best solution will be
public class User {
Set<UserLogin> users = new HashSet<UserLogin>();
public static void main(String[] arg) throws IOException {
BufferedReader bReader =new BufferedReader(new InputStreamReader(System.in));
String name = bReader.readLine();
String login = bReader.readLine();
String password = bReader.readLine();
new User().UserADD(new User(). new UserLogin(name, login, password));
}
private void UserADD(final UserLogin user) {
if (!users.contains(user)) {
users.add(user);
} else {
System.out.println("Это имя пользователя уже занято");
}
}
public class UserLogin {
private String name;
private String login;
private String pass;
public UserLogin(String name, String login, String pass) {
this.name = name;
this.login = login;
this.pass = pass;
}
public String getName() {
return name;
}
public String getLogin() {
return login;
}
public String getPass() {
return pass;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserLogin user = (UserLogin) o;
return !(login != null ? !login.equals(user.login) : user.login != null);
}
#Override
public int hashCode() {
return login != null ? login.hashCode() : 0;
}
}
}
Thank you all very much, but the problem remained. When you try to second user to input a username first, the program accepts it calmly, ignoring any restrictions and a warning on the screen does not come out. I tried all the options.
class Test{
public static void main(String args[])
{
Patron list[] = new PatronData().getPatronData();
/*for(Patron p: list)
{
System.out.println(p);
}*/
}
}
class PatronData{
//Patron patron[] = {new Patron("Daniel","A001","15WAD00001","A4701,Jalan Kepong, Pahang","JK01",0.00,"012-8765432"),
// new Patron("Chiam","A002","15WAD00002","A4702,Jalan Akar,Pahang","JK02",0.00,"0102288554")};
Patron patron[] = new Patron[2];
public Patron[] getPatronData()
{
patron[0] = new Patron("Daniel","A001","15WAD00001","A4701,Jalan Kepong, Pahang","JK01",0.00,"012-8765432");
patron[1] = new Patron("Chiam","A002","15WAD00002","A4702,Jalan Akar,Pahang","JK02",0.00,"0102288554");
return patron;
}
}
class Patron{
private String userName;
private String password;
private String userCode;
private String streetAddress;
private String postCode;
private double overdueBalance;
private String phoneNumber;
Patron(String userName[], String password[], String userCode,
String streetAddress, String postCode, double overdueBalance, String phoneNumber)
{
this.userName = userName;
this.password = password;
this.userCode = userCode;
this.streetAddress = streetAddress;
this.postCode = postCode;
this.overdueBalance = overdueBalance;
this.phoneNumber = phoneNumber;
int logNMatch = 0;
Scanner scan = new Scanner(System.in);
do{
System.out.print("Please Enter Your User Name > ");
String inputUserName=scan.nextLine();
System.out.println();
System.out.print("Please Enter Your Password > ");
String inputPassword = scan.nextLine();
if(userName.compareTo(inputUserName) == 0 && password.compareTo(inputPassword) == 0)
{
System.out.println("Logging Successful");
System.out.print("\n\n");
}
else
{
System.out.println("Loging fail");
System.out.println("Please again later");
logNMatch++;
}
}while(logNMatch > 0);
}
}
Hey guys, I am learning Java in Diploma Level. I have a question.
Please, I have no idea why I cannot straight away logging into "Chiam Account"I expected is when i log in the compiler will automatically check whether is the login detail match with the data in library system.
You are requesting the login information inside the constructor. Meaning that whenever you make a new Patron it will prompt you to login with that user's information.
Instead remove everything inside that do/while loop and add a method like loginFromLibrary() that will prompt the user to input their name and password. Then check all of the Patrons to see if any of their names match the username given. Then just make sure that the username matches the password.
This example will require some getter (getPassword() and getUsername()):
public void loginFromLibrary(Patron[] patrons){
Scanner scan = new Scanner(System.in);
while (true){
// get usernmae
System.out.println("Username > ");
String username = scan.nextLine();
Patron user = null;
// check array to see if username exists
for (Patron p : patrons){
if (p.getUsername().equals(username)){
user = p;
break;
}
}
if (user == null){
// username not found
System.out.println("Username not found");
continue;
}
// get password
System.out.println("Password > ");
String pass = scan.nextLine();
// check password
if (pass.equals(user.getPassword())){
// logged in
break;
} else {
// wrong password
}
}
scan.close();
}