Java Check if multiple strings are empty - java

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, ...);
// ...
}

Related

Check if username is already registered in ArrayList

I have this JFrame program that just registers users by their full name, username, city, age. I have the checks for the text fields in a method. If you press the register JButton, then it checks if you have entered the information correctly and then creates a new User to an array list.
I need to add a check, that will tell me when I press the Register button if the username exists. I tried making an if statement in my method for checking my text fields right before a new user is created in the area list, but it is just ignored. I tried to make that if statement before the method for the Register button and still nothing. I will paste my Action Listener code below, with my methods.
Edit: posting the method that I use for more clarity.
public void fieldChecks()
{
if(fullnameField.getText().length() < 6)
{
Helpers.showError("Name must have at least 7 characters");
return;
}
if(usernameField.getText().length() < 4)
{
Helpers.showError("Username must have at least 4 characters!");
return;
}
if(cityField.getText().length() < 5)
{
Helpers.showError("City must have at least 5 characters");
return;
}
if(passwordField.getText().length() < 8)
{
Helpers.showError("Name must have at least 8 characters");
return;
}
if(ageField.getText().length() == 0)
{
Helpers.showError("Age is a required field!");
return;
}
//check if our boolean is true or false from Helpers class
if(Helpers.ageCheck(ageField.getText()) == false)
{
Helpers.showError("Age must be a whole number!");
return;
}
String fullname = fullnameField.getText();
String username = usernameField.getText();
String city = cityField.getText();
String password = passwordField.getText();
int age = Integer.parseInt(ageField.getText());
String sex = " ";
//check which radio button is selected
if(maleOption.isSelected())
{
sex = "Male";
}else
{
sex = "Female";
}
//we have to create a user now by having the above new vars in the user brackets in order of our Class constructor
User myUser = new User(fullname,username, city, password, sex, age);
//create the default add function for our arraylist that we added in the vars above
myUsers.add(myUser);
Helpers.showConfirmation("User added!");
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == registerButton)
{
//this method checks if my text fields have more
//than X charactes typed before it creates a user.
// This method also adds the new user to my array list
//after the checks are complete
fieldChecks();
}
else if(e.getSource() == printButton)
{
printUser();
}
else if(e.getSource() == searchButton)
{
searchUsers();
}
After:
if(usernameField.getText().length() < 4)
{
Helpers.showError("Username must have at least 4 characters!");
return;
}
I would verify if that username is taken with following code
if(myUsers.size() > 0)
{
for(User user : myUsers)
{
if(usernameField.getText() == user.username)
{
Helpers.showError("This username is taken");
return;
}
}
}
I assume that myUser is an ArrayList of type myUser. You want to override equals method in your myUser class and then call contains. Look up how to #Override equals but here is a short demonstration.
public static void main(String[] args) {
List<myUser> users = new ArrayList<>();
users.add(new myUser("Billy", "xBillx"));
List<myUser> usersToAdd = new ArrayList<>();
usersToAdd.add(new myUser("Jill", "jilly"));
usersToAdd.add(new myUser("Billy", "xBillx"));
for(myUser newUser : usersToAdd){
if(!users.contains(newUser)){
users.add(newUser);
System.out.println("New user added: " + newUser.fullname);
} else {
System.out.println("User already exists " + newUser.fullname);
}
}
}
static class myUser{
final private String fullname;
final private String username;
myUser(String fullName, String username){
this.fullname = fullName;
this.username = username;
}
#Override
public boolean equals(Object user){
if(user == this){
return true;
}
if(user instanceof myUser &&
this.username.equals(((myUser) user).username) &&
this.fullname.equals(((myUser) user).fullname)) {
return true;
}
return false;
}
}
it prints:
New user added: Jill
User already exists Billy
Edit: made a mistake, you can't compare strings with == in Java

Creating multiple choice for user

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);
}
}
}

How can I use method abstraction for checking userInput against login details?

We worked progressively on a project. Last milestone is dividing this into the following: Create a class with four methods: main method, a method for creating customer information(void), a method for creating user name and password (void) and finally a method for log-in(return type).
I have implemented the log-in method, when moving to implementation of the loginDetails, I ran into problems. I don't understand how I can create loginDetails in a void method, and also be able to check against it in a different method. My loginDetail method is not returning a value to main, and my variables are local for the methods.
How can I create the user details in a void method, and be able to create the login check in a separate method?
This is my code, I would like to use the details generated in loginDetails(); as the values to check against instead of the manually inserted strings.
public class Customer {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
String userName, password;
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}
class Customer {
static Scanner input = new Scanner(System.in);
static String userName=null;
static String password=null;
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}

Library System Login Logout

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();
}

NullPointerException on a static attribute

I am creating a simple login program in java. Here is the code i have so far.
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class PasswordProgram {
public static String user;
public String password;
public static boolean part1Finish = false;
public File file = new File("D:/file.txt");
public FileWriter UsernameWrite;
public char[] user1;
public void part1() {
System.out.println("Please create an account: ");
Scanner input = new Scanner(System. in );
System.out.println("Type in a username: ");
String user = input.next();
System.out.println("Type in a Password: ");
String password = input.next();
try {
UsernameWrite = new FileWriter(file);
UsernameWrite.write(user);
UsernameWrite.write(password);
System.out.println(user);
UsernameWrite.close();
part1Finish = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void part2() {
Scanner scan = new Scanner(System. in );
System.out.println("Please confirm your username: ");
String usercheck = scan.next();
int PassAttempts = 5;
int UserAttempts = 5;
user1 = user.toCharArray();
user1 = password.toCharArray();
char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length());
System.out.println(usernamecheck);
do {
if (usercheck.equals(usernamecheck)) {
while (PassAttempts > 0) {
System.out.println("Please confirm your password: ");
String passcheck = scan.next();
if (passcheck.equals(password)) {
System.out.println("Thank You ");
} else if (passcheck != password && PassAttempts > 0) {
PassAttempts--;
System.out.println("That is incorrect. Please Try Again");
passcheck = scan.nextLine();
} else {
System.out.println("You have run out of Password Attempts");
break;
}
}
} else if (usercheck != user && UserAttempts > 0) {
UserAttempts--;
System.out.println("That is an incorrect username. Please Try Again");
usercheck = scan.nextLine();
} else {
System.out.println("You have run out of Username Attempts");
break;
}
} while (UserAttempts > 0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PasswordProgram login = new PasswordProgram();
login.part1();
if (part1Finish == true) {
login.part2();
}
}
}
The problem i am getting is in the method part2. Here when I try to add the username that was saved under the variable user into a character array to use it as a range I get the error NullPointerException.
After investigating i see that when running part2 the value of user is null and therefore I get the error.
Is there a way I could do this through the FileReader method instead or how can i fix the current error I am getting ? Thank you.
Because the static field user is never assigned in part1, you get a NullPointerException when you try to use it in part2.
There are also other issues in the posted code:
why there is a file involved is unclear
you use != with String, for example in passcheck != password
you use equals between String and char[] in usercheck.equals(usernamecheck)
passcheck is assagned but never used
local variables (because of their names) are hiding some fields
UsernameWrite and UserAttempts have non conventional names (should be usernameWrite and userAttempts
You have two user variables declared, one which is static and has global scope, another which is local to part1(). When part2() is attempting to access user, it is using the static declaration, which is null. Your modifications to user in part1() are done to the local variable.
This is something called variable shadowing and should be avoided at all costs.
See the below example:
class Ideone
{
static String bla = "test1";
public static void myMethod() {
String bla = "test2";
System.out.println(bla);
}
public static void main (String[] args) throws java.lang.Exception
{
myMethod();
System.out.println(bla);
}
}
It outputs:
test2
test1

Categories

Resources