ArrayList seems not to contain anything - java

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.

Related

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

Matching the index of username and index of password in 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;
}
}
}

How to read from a file and send it to a constructor in Java

I have a code that reads an id block of three lines from a text file, I want to split those lines in Strings and an int, and pass this to a constructor from another class.
Right now, this class asks for an id number and prints everything below the # sign, down to and including the third line of each id block. I want those three lines in each id to be parsed as 'name', 'age' and 'job' to an Employee class, in order to create an object of the id, like this: Employee("Richard Smith",22,"Electric engineer"). There will always be three lines in the file for an id, so how can I "find" those lines and split them into Strings and an int?
#1000
Richard Smith
22
Electric engineer
#1001
Elliot Smith
23
Physicist
public class RdB
{
String b; //file name
RdB(String ename) {
b = ename;
}
//info about an employee
boolean showE (String id) {
int ch;
String code, info;
//open the file with the info
try (BufferedReader showERdr =
new BufferedReader (new FileReader(b)))
{
do {
//read characters until a '#' is found
ch = showERdr.read();
//check
if(ch == '#') {
code = showERdr.readLine();
if(id.compareTo(code) == 0) { //found employee
do {
info = showERdr.readLine();
if(info != null) {
System.out.println(info);
}
} while(((info != null) &&
(info.compareTo("") != 0)));
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
System.out.println("File error!");
return false;
}
return false; //employee not found
}
//Access a registered employee
String getE() {
String id = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter id number: ");
try{
id = br.readLine();
}
catch(IOException exc) {
System.out.println("Access error");
}
return id;
}
}
Edit:
Employee class
class Employee {
private String name, job;
private int age;
public Employee (String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getJob () {
return job;
}
}
You can simply use an ArrayList to save what you read from the file and process it later. Since you are certain about the features of your saved file that it will always contain 3 lines before the line which contains ID, here is the working code I wrote to solve your problem. You can see the output wrapped between ( )
Here is the code:
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class Emp{
public static void main(String[] args) throws IOException{
List data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("PeopleData.txt"));
String str;
while((str = reader.readLine()) != null){
// System.out.println(str);
data.add(str);
}
for(int i= 0; i< data.size(); i ++){
i++;
System.out.println("(");
System.out.println(data.get(i));
String name = (String) data.get(i);
i++;
System.out.println(data.get(i));
int age = Integer.valueOf((String) data.get(i));
i++;
System.out.println(data.get(i));
String job = (String) data.get(i);
i++;
System.out.println(")");
//new Employee(name, age, job);
}
}
}

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

I need to get a file reader to read a text file line by line and format them in Java

I have a text file, formatted as follows:
Han Solo:1000
Harry:100
Ron:10
Yoda:0
I need to make an arrayList of objects which store the player's name (Han Solo) and their score (1000) as attributes. I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes.
I tried using a Scanner object, but didn't get far. Any help on this would be greatly appreciated, thanks.
You can have a Player class like this:-
class Player { // Class which holds the player data
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Getters & Setters
// Overrride toString() - I did this. Its optional though.
}
and you can parse your file which contains the data like this:-
List<Player> players = new ArrayList<Player>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(":"); // Split on ":"
players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
}
} catch (IOException ioe) {
// Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
You can create a Class call player. playerName and score will be the attributes.
public class Player {
private String playerName;
private String score;
// getters and setters
}
Then you can create a List
List<Player> playerList=new ArrayList<>();
Now you can try to do your task.
Additionally, you can read from file and split each line by : and put first part as playerName and second part as score.
List<Player> list=new ArrayList<>();
while (scanner.hasNextLine()){
String line=scanner.nextLine();
Player player=new Player();
player.setPlayerName(line.split(":")[0]);
player.setScore(line.split(":")[1]);
list.add(player);
}
If you have Object:
public class User
{
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
Make an Reader class that reads from the file :
public class Reader
{
public static void main(String[] args)
{
List<User> list = new ArrayList<User>();
File file = new File("test.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
String[] splitedString = line.split(":");
User user = new User();
user.setName(splitedString[0]);
user.setScore(Integer.parseInt(splitedString[1]));
list.add(user);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for (User user : list)
{
System.out.println(user.getName()+" "+user.getScore());
}
}
}
The output will be :
Han Solo 1000
Harry 100
Ron 10
Yoda 0
Let's assume you have a class called Player that comprises two data members - name of type String and score of type int.
List<Player> players=new ArrayList<Player>();
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("filename"));
String record;
String arr[];
while((record=br.readLine())!=null){
arr=record.split(":");
//Player instantiated through two-argument constructor
players.add(new Player(arr[0], Integer.parseInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
For small files (less than 8kb), you can use this
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NameScoreReader {
List<Player> readFile(final String fileName) throws IOException
{
final List<Player> retval = new ArrayList<Player>();
final Path path = Paths.get(fileName);
final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
for (final String line : source) {
final String[] array = line.split(":");
if (array.length == 2) {
retval.add(new Player(array[0], Integer.parseInt(array[1])));
} else {
System.out.println("Invalid format: " + array);
}
}
return retval;
}
class Player {
protected Player(final String pName, final int pScore) {
super();
this.name = pName;
this.score = pScore;
}
private String name;
private int score;
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getScore()
{
return this.score;
}
public void setScore(final int score)
{
this.score = score;
}
}
}
Read the file and convert it to string and split function you can apply for the result.
public static String getStringFromFile(String fileName) {
BufferedReader reader;
String str = "";
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
str = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
String stringFromText = getStringFromFile("C:/DBMT/data.txt");
//Split and other logic goes here
}

Categories

Resources