Matching the index of username and index of password in java - java

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

Related

Exception after using refractor - Java in Eclipse

I need to update my project, I used a lowercase on classes and its not standard coding convention. So, I have used the refractor > rename in eclipse for the classes. And now I get this exception/error:
Exception in thread "main" java.lang.NoClassDefFoundError:
FacebookClass/facebookClass (wrong name: FacebookClass/FacebookClass)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookClass.Driver.main(Driver.java:28)
I used the refractor and had the box checked to change all names, I don't know what the problem is.
Driver Class:
package FacebookClass;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Driver {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String username;
String password;
int choice = 0;
FacebookClass facebook = new FacebookClass();
String filename = "save.ser";
// Deserializing facebook object
try
{
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
facebook = (FacebookClass)in.readObject();
in.close();
file.close();
System.out.println("Succefully opened saved data.");
}
catch(IOException ex)
{
}
catch(ClassNotFoundException ex)
{
}
while (choice != 5)
{
choice = menu();
switch(choice)
{
case 1:
// List users
System.out.println("");
facebook.listUsers();
break;
case 2:
// Add a user
System.out.println("");
System.out.print("Enter a username: ");
username = input.nextLine();
facebook.addUser(username);
break;
case 3:
// Delete a user
System.out.print("Enter your username: ");
username = input.nextLine();
facebook.deleteUser(username);
break;
case 4:
// Get password hint
System.out.print("Enter your username: ");
username = input.nextLine();
facebook.getHint(username);
break;
case 5:
// Quit and serialize facebook object
try
{
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(facebook);
out.close();
file.close();
System.out.println("Data has been saved.");
}
catch(IOException ex)
{
}
}
}
}
public static int menu()
{
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("");
System.out.println("1) List Users");
System.out.println("2) Add a User");
System.out.println("3) Delete a User");
System.out.println("4) Get Password Hint");
System.out.println("5) Quit");
System.out.print("Enter your choice: ");
choice = input.nextInt();
while (choice < 1 || choice > 5)
{
System.out.print("Try again: ");
choice = input.nextInt();
}
return choice;
}
}
FacebookClass Class:
package FacebookClass;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class FacebookClass implements Serializable
{
private ArrayList<FacebookUser> users = new ArrayList<FacebookUser>();
public void listUsers()
{
// Print user names of users array list
System.out.println("Users: ");
for (int i=0; i<users.size(); i++)
{
System.out.println((users.get(i)).getUsername());
}
}
public void addUser(String username)
{
Scanner input = new Scanner(System.in);
String password;
String hint;
// Add a user, check if name exists
Boolean nameCheck = false;
for (int i=0; i<users.size(); i++)
{
if (users.get(i).getUsername().equals(username))
{
nameCheck = true;
}
}
if (nameCheck)
{
System.out.println("Error! Username is already in
use.");
}
else
{
System.out.print("Enter a password: ");
password = input.nextLine();
System.out.print("Enter a password hint: ");
hint = input.nextLine();
FacebookUser user = new FacebookUser(username,
password);
user.setPasswordHint(hint);
users.add(user);
}
}
public void deleteUser(String username)
{
Scanner input = new Scanner(System.in);
String passwordTemp;
Boolean usernameCheck = false;
Boolean passwordCheck = false;
for (int i=0; i<users.size(); i++)
{
if ((users.get(i)).getUsername().equals(username))
{
System.out.print("Enter your password to
confirm: ");
passwordTemp = input.nextLine();
usernameCheck = true;
if
(!passwordTemp.equals(users.get(i).getPassword()))
{
System.out.println("Error! Passwords do
not match.");
usernameCheck = false;
passwordCheck = true;
}
if (!passwordCheck)
{
users.remove(i);
}
}
}
if (usernameCheck)
{
System.out.println("User has been succesfully
deleted.");
}
else if (!usernameCheck && !passwordCheck)
{
System.out.println("The entered username does not match
any users.");
}
}
public void getHint(String username)
{
Boolean nameCheck = false;
for(int i=0; i<users.size(); i++)
{
if (users.get(i).getUsername().equals(username))
{
users.get(i).getPasswordHelp();
nameCheck = true;
}
}
if (!nameCheck)
{
System.out.println("The entered username does not match
any users.");
}
}
}
FacebookUser Class:
package FacebookClass;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.*;
import java.lang.*;
import java.io.*;
public class FacebookUser extends UserAccount implements Cloneable,
Comparable<FacebookUser>, Serializable {
public FacebookUser(String username, String password) {
super(username, password);
}
private String passwordHint;
private ArrayList<FacebookUser> friends = new ArrayList<FacebookUser>
();
void setPasswordHint(String hint)
{
passwordHint = hint;
}
void friend(FacebookUser newFriend)
{
// Check if friend is in friends list. If not, add them
Boolean friendCheck = false;
for (int i = 0; i < friends.size(); i++)
{
if (friends.get(i) == newFriend)
{
friendCheck = true;
}
}
if (friendCheck)
{
System.out.println(newFriend.getUsername() + " is already are on " +
this.getUsername() + "'s friends list!");
}
else
{
friends.add(newFriend);
System.out.println(this.getUsername() +
"'s friend list: " + friends);
}
}
void defriend(FacebookUser formerFriend)
{
// Check if friend is in friends list. If they are, remove them
Boolean friendCheck = false;
for (int i = 0; i < friends.size(); i++)
{
if (friends.get(i) == formerFriend)
{
friendCheck = true;
}
}
if (!friendCheck)
{
System.out.println("They are not on friends list!");
}
else
{
friends.remove(formerFriend);
System.out.println(this.getUsername() + "'s friend
list: " + friends);
}
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
ArrayList<FacebookUser> getFriends()
{
// Create clone of face book users array list and return
ArrayList<FacebookUser> clone = (ArrayList) friends.clone();
return clone;
}
// Compare to method for sorting
#Override
public int compareTo(FacebookUser user) {
return
this.getUsername().compareToIgnoreCase(user.getUsername());
}
// Abstract get password help method
#Override
public void getPasswordHelp()
{
if (!(passwordHint == null))
{
System.out.println(this.getUsername() + "'s password
hint is: "+ passwordHint);
}
else
{
System.out.println(this.getUsername() + "'s password
hint has not been set");
};
}
}
UserAccount Class:
package FacebookClass;
import java.io.Serializable;
import FacebookClass.UserAccount;
public abstract class UserAccount implements Serializable
{
private String username = "";
private String password = "";
private Boolean active = false;
public abstract void getPasswordHelp();
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public void createAccount(String username, String password)
{
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password)
{
if (password.equals(this.password))
{
return true;
}
else
{
return false;
}
}
public void deactivateAccount()
{
active = false;
}
public String toString()
{
return (username);
}
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;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 :
username.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null)
{
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}

Why does my recursive method make my program throw an InvalidClassException?

In my program, I have a FacebookUser class that has an ArrayList of all of that user's friends. All of those friends may also have friends. I am using recursion to get a new ArrayList that contains all of the user's friends and all of the user's friends' friends and so on. I also serialized the FacebookUser class so I can save the data. Without the new recursive method, I can serialize without error and the data persists over executions. With the recursive method, though, I get an InvalidClassException. It shows that the exception is at the line that uses the ObjectInputStream to get the FacebookUser from memory.
I'm not understanding why the new method is causing the exception to be thrown from another method. I believe the problem lies only in the FacebookUser.java class (since getRecommendations is recursive method) but I thought it'd be best to also show the UserAccount.java class since the former extends the latter. Any help will be appreciated. Thank you.
Execution:
Exception in thread "main" java.io.InvalidClassException: FacebookUser; local class incompatible: stream classdesc serialVersionUID = 4110981517967863740, local class serialVersionUID = 5032562666539812166
at java.base/java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject0(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookUser.readFile(FacebookUser.java:157)
at DriverClass.main(DriverClass.java:12)
FacebookUser.Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class FacebookUser extends UserAccount implements Serializable{
private String passwordHint;
private ArrayList<FacebookUser> friends;
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
public void getPasswordHelp(String username) {
if (friends.size() == 0) {
System.out.println("There is no user with that username.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
friends.get(i).getPasswordHelp();
break;
}
if (i == friends.size() - 1) {
System.out.println("There is no user with that username.");
break;
}
}
}
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
if (friends.contains(newFriend)) {
System.out.println("That person is already your friend.");
} else {
friends.add(newFriend);
}
}
void friend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("That person is already your friend.");
break;
}
if (i == friends.size() - 1) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
break;
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.contains(formerFriend)) {
friends.remove(formerFriend);
} else {
System.out.println("That person is not your friend.");
}
}
void defriend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("That person is not your friend.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("Password for " + username + ": ");
String passw = s.nextLine();
if (friends.get(i).getPassword().equals(passw)) {
friends.remove(i);
break;
} else {
System.out.println("Incorrect Password");
break;
}
}
if (i == friends.size() - 1) {
System.out.println("That person is not your friend.");
break;
}
}
}
}
ArrayList<FacebookUser> getRecommendations(FacebookUser friend) {
ArrayList<FacebookUser> recFriends = new ArrayList<FacebookUser>();
for (int i = 0; i < friend.getFriends().size(); i++) {
for (int j = 0; j < recFriends.size(); j++) {
for (int k = 0; k < recFriends.size(); k++) {
if (recFriends.get(j).equals(recFriends.get(k))) {
recFriends.remove(j); // This removes any duplicate friends so there won't be an infinite loop.
break;
}
}
}
recFriends.addAll(friend.getFriends().get(i).getRecommendations(friend)); // This adds the friends' friends' friends and so on into the ArrayList.
}
return recFriends;
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
Collections.sort(friendsCopy, new Comparator<FacebookUser>() {
#Override
public int compare(FacebookUser fb1, FacebookUser fb2) {
return fb1.toString().compareToIgnoreCase(fb2.toString());
}
});
return friendsCopy;
}
public static void writeToFile(FacebookUser facebookUser) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FacebookUser.bin"));
oos.writeObject(facebookUser); // This saves the data.
}
public static FacebookUser readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FacebookUser.bin"));
FacebookUser facebookUser = (FacebookUser) ois.readObject(); // This reads in the data which is called in the DriverClass class line 12.
return facebookUser;
}
}
UserAccount.java
import java.io.Serializable;
public abstract class UserAccount implements Serializable{
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String getPassword() {
return password;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
DriverClass.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class DriverClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int choice = 0;
String username;
FacebookUser fu0;
try {
fu0 = FacebookUser.readFile();
} catch (FileNotFoundException e) {
fu0 = new FacebookUser("Robert", "password1");
}
while (choice != 5) {
System.out.println(
"1. List Users \n2. Add a User \n3. Delete a User \n4. Get Password Hint \n5. Get Recommendations \n6. Quit");
Scanner s = new Scanner(System.in);
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println(fu0.getFriends());
break;
case 2:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.friend(username);
break;
case 3:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.defriend(username);
break;
case 4:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.getPasswordHelp(username);
break;
case 5:
System.out.println(fu0.getRecommendations(fu0));
break;
case 6:
FacebookUser.writeToFile(fu0);
break;
}
}
}
}
The exception suggests that the SerialVersionUID the JVM generated differs for some instances of the FacebookUser object. If you make your class implement Serializable, it is highly recommended that you explicitly declare the SerialVersionUID variable to avoid exceptions like these.
So in the FacebookUser class you should declare a variable like this:
private static final long serialVersionUID = 42L;
See this answer for more details.

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

ArrayList seems not to contain anything

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.

Standard FTP Login java class

Is there a defined standard class for dealing with FTP login data? Something that already handles storing, sharing? Since I am relatively new to this, maybe someone else gave this topic already a thorough thinking. Could not find anything in Apache Commons so far...
For now I use my own class, it is not very fulfilling:
public class FTPLogin {
String hostaddress;
int port;
String name;
String password;
public FTPLogin() {
}
public FTPLogin(String hostaddress, int port, String name,
String password) {
this.hostaddress = hostaddress;
this.port = port;
this.name = name;
this.password = password;
}
#Override
public String toString() {
return hostaddress + ";" + port + ";" + name + ";" + password;
}
}
There is no Standard, I prefer ftp4j
import java.util.Scanner;
class users
{
String username;
String password;
String[][] accounts = {{"Karthik", "k123"},{"Ram", "r123"}};
users(String user, String pass)
{
username = user;
password = pass;
}
public boolean auth()
{
if((username == accounts[0][0]) && (password == accounts[0][1]))
{
return true;
}
else if((username == accounts[1][0]) && (password == accounts[1][1]))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter name:");
String s=sc.next();
System.out.println("Enter pid:");
int i=sc.nextInt();
users obj=new users(s,i);
System.out.println(obj.auth());
}
}
import java.util.Hashtable;
import java.util.Scanner;
class Login
{
public boolean checkValue(String name,String Password)
{
Hashtable<String,String> map=new Hashtable<String,String>();
map.put(name,Password);
//System.out.println(map);
if(name.equals("abcd") && Password.equals("1234"))
{
return true;
}
else if(name.equals("Mnop") && Password.equals("5678"))
{
return true;
}
else if(name.equals("xyzx") && Password.equals("7890"))
{
return true;
}
else
{
return false;
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a name s:");
String s=sc.next();
System.out.println("Enter a password p:");
String p=sc.next();
Login obj=new Login();
boolean status=obj.checkValue(s,p);
System.out.println(status);
}
}

Categories

Resources