after some research and help from a friend I could make a method (authentificate) that compare the username and password given by the user in the Main and the ones presents in the loginList. The problems is the methode always return false, and I can't find the problem.
Thanks in advance for your help.
Main
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String username;
String password;
System.out.println("Enter your username");
username = input.nextLine();
System.out.println("Enter your password");
password = input.nextLine();
UserList test2 = new UserList();
if (test2.authenticate(username, password) == true) {
System.out.println("Hi");
} else {
System.out.println("Username or/and password are wrong.");
}
}
}
User
public class User {
protected String username;
protected String password;
public User(String username, String password) {
this.password = password;
this.username = username;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (o instanceof User) {
return ((User) o).username.equals(username);
}
return false;
}
#Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.username);
return hash;
}
}
UserList
public class UserList {
private HashSet<User> loginList;emphasized text
public UserList() {
Scanner scan;
loginList = new HashSet();
try {
scan = new Scanner(new File("src/boitedejeux/Logins.txt"));
String ligne = scan.nextLine();
while (scan.hasNext()) {
ligne = scan.nextLine();
String[] res = ligne.split(",");
loginList.add(new User(res[0], (res[1])));
}
} catch (FileNotFoundException e) {
System.out.println("Erreur");
}
}
public boolean authenticate(String username, String password) {
if (null == loginList) {
throw new IllegalStateException("The user list isn't initialised");
}
return loginList.stream()
.filter(usern -> usern.getUsername().equals(username))
.filter(passw -> passw.getPassword().equals(password))
.findFirst()
.isPresent();
}
}
Login.txt
Test, Password
Test2, Password2
Remove spaces after commas in your txt, or change the line of String[] res = ligne.split(",") to split with spaces String[] res = ligne.split(", ").
Related
I have created a login system with some "preset" users. I would like to alter my code to be able to create new user(s) inside the system and add them to my user list. How can I do this? I am a beginner in Java so help will be appreciated.
LoginSystem class:
package logpack;
import java.util.ArrayList;
import java.util.Scanner;
public class LoginSystem {
ArrayList<User> users = new ArrayList<User>();
public boolean run() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter username: ");
String inpUser = keyboard.nextLine();
System.out.println("Enter password: ");
String inpPass = keyboard.nextLine(); // gets input from user
boolean loginSuccess = false;
for (User temp : users) {
if (inpUser.equals(temp.getUsername()) && inpPass.equals(temp.getPassword())) {
System.out.println("Welcome " + temp.getName() + " to the System.");
loginSuccess = true;
break;
} else {
loginSuccess = false;
}
}
if (loginSuccess == false) {
System.out.println("Incorrect Input, Try again.");
}
return loginSuccess;
}
public void saveUser(User US) {
users.add(US);
}
public ArrayList<User> getUsers() {
return users;
}
}
User class:
package logpack;
public class User {
String name;
String username;
String password;
public User(String name, String username, String password) {
this.username = username;
this.password = password;
this.name = name;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
protected String getUsername() {
return username;
}
protected void setUsername (String username) {
this.username = username;
}
protected String getPassword() {
return password;
}
protected void setPassword (String password) {
this.password = password;
}
}
RunClass class(the one I have to alter to create a kind of "register" system):
package logpack;
public class RunClass {
public static void main(String[] args) {
LoginSystem LGS = new LoginSystem();
System.out.println("Enter username: ");
////////
User u1 = new User("Daria", "Daria5", "12345");
User u2 = new User("Bob", "Bob8989 ", "Bob64748od7");
User u3 = new User("Samanta", "Sam764", "678303");
User u4 = new User("Dog", "Doggy998621", "C6574");
User u5 = new User("Doughnut", "DBghf", "pae102938");
LGS.saveUser(u1);
LGS.saveUser(u2);
LGS.saveUser(u3);
LGS.saveUser(u4);
LGS.saveUser(u5);
///////
/*Can you replace this section above with a loop and method that asks
* the user if they want to create a new user account? As many as they want?
* This is inefficient as we have to write many lines to create many users.
* It does mean that we always have users to start with to simulate
* having a save file.
*/
LGS.run();
//System.out.println("User list: "+LGS.users);
}
}
Thank you very much for your help!
In your main class, instead of prompting the user to enter username, prompt the user with a list of options and the user either select login or registration, e.g:
public static void main(String[] args) {
// create a scanner to read the command-line input
Scanner scanner = new Scanner(System.in);
int optionSelected;
do {
System.out.println("Select 1 for Login");
System.out.println("Select 2 for User Registration");
System.out.println("Select 3 to Exit");
System.out.print("Enter selected option: ");
optionSelected = scanner.nextInt();
if(optionSelected == 1){
// proceed with login
System.out.println("Login in progress\n");
} else if (optionSelected == 2){
// proceed with registration
System.out.println("Registration in progress\n");
}
} while (optionSelected != 3);
}
It is not the best code in the world, but it will help you out. For now there are only 3 options, later you can add more options.
Below is my user Class. I also have a Card class which is the parent class of a Single currency card class and a multi card currency class.
I am fairly new to coding and have trouble understanding some concepts. What I need to do is return the cards that the user owns if the username and password match. This is in the getCards method. After this, i need to add the card to the Hashmap list if the username and password match. Any tips or other sites that would really help as I struggle a lot with the HashMap concept.
public class User {
String username;
String password;
User user;
HashMap<String,Card> userHash = new HashMap <String, Card>(); //key is the cardID
public User(String username, String password)
{
this.username = username;
this.password = password;
}
public String toString()
{
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(user.getUsername()) && password.contains(user.getPassword()))
{
System.out.println("User accepted");
return true;
}else
System.out.println("Access denied");
return false;
}
public HashMap<String, Card> getCards(String username, String password)
{
for(String value : userHash.keySet())
if (user.userValidate(username, password) == true)
{
//return user's cards
return true;
}else
return null;
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(user.userValidate(username, password) == true)
{
user.getCards(username, password);
}
return false;
}
The card which belongs to the user
Here is my design concept.
In this case, the user class can have many cards and each card has an id.
The validation check must be saved every time when creation user.
The userValidate method can be checked the arguments with its own values then save it to isvalid variable(boolean).
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
The getCards method is simple because it checks that the isvalid is true or not.
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
The addCard method, I can just save the card with card id, if user validation is success or nothing...
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
So, come together with all these codes.
import java.util.HashMap;
class Card
{
private String cardId;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
public class User {
private String username;
private String password;
private boolean isvalid;
HashMap<String, Card> userHash = new HashMap<String, Card>(); // key is the
// cardID
public User(String username, String password) {
this.username = username;
this.password = password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
public String toString() {
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
}
You can iterate over the map and add all cards to a list:
List<Card> list = new ArrayList();
for (Map.Entry<String, Card> entry : userHash.entrySet()) {
if(entry.getKey().equals(username)) { list.add(entry.getValue(); }
}
Is that what you were looking for?
Or if you already understood streams:
userHash.entrySet().stream().filter(entry -> username.equals(entry.getValue())
.map(Entry::getKey)
.collect(toList());
After the user is registered, they can login which is supposed to read their details from a text file by using a BufferedReader. However, I am unsure of how to use a BufferedReader to read the arraylist of User objects line by line to check the details are in the text file and allow for the user to login.
This is what I have written:
public class LoginJFrame extends javax.swing.JFrame {
ArrayList<User> users = new ArrayList<>();
public LoginJFrame() {
initComponents();
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
String nickname = edtNickname.getText();
String loginID = edtLoginID.getText();
String password = String.valueOf(edtPassword.getPassword());
try {
BufferedReader br = new BufferedReader(new FileReader("userinfo.txt"));
String readFile = br.readLine();
while (readFile != null) {
String[] splitString = readFile.split(",");
nickname = splitString[0];
loginID = splitString[1];
password = splitString[2];
User user = new User(nickname, loginID, password);
users.add(user);
readFile = br.readLine();
this.dispose();
ThreadJFrame threadPage = new ThreadJFrame();
threadPage.setVisible(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The only reason why I have another arrayList that is a string is because I cannot figure out a way for the BufferedReader to read my User arrayList line by line. Is there a way for the BufferedReader to read the arraylist class type instead of a string ArrayList?
The User object is a separate class that stores the nickname, login ID and password by using a string.
public class User {
String nickname;
String loginID;
String password;
public User(String nickname, String loginID, String password) {
this.nickname = nickname;
this.loginID = loginID;
this.password = password;
}
public String getNickname() {
return nickname;
}
public String getLoginID() {
return loginID;
}
public String getPassword() {
return password;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void setLoginID(String loginID) {
this.loginID = loginID;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" + "nickname= " + nickname + ", loginID= " + loginID + ", password= " + password + '}';
}
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
}
Well, that code only reads a single line since you only ever invoke the readline() method once.
The code should be something like:
currentLine = br.readLine();
while (currentLine != null) {
userstring.add(currentLine);
currentLine = br.readLine();
}
And since your data for the User is contained in a single line (since you just save the toString() of your User class) you will need to parse the data into its individual tokens probably by using the String.split(...) method.
Of course your readToFile(...) method won't really do anything because you define the ArrayList locally and don't return any data from the method so the rest of your class can't access the data.
I am trying to read an API link which contains data of JSON format. this is what i am trying to read and display on the phone:
[[],{"index":"2","name":"jim","email":"jim#outlook.com","contact":"0122511336","username":"jim","password":"jim","photo":"student.jpg","status":"Active"}]
The program supposed to authenticate the username and password inputs and this dipsplay the content of the above from URL.
Below is the codes and so far what I have done. Please someone help me to get this through.
package org.json.me;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Login extends MIDlet implements CommandListener {
private String name;
private String email;
private int contact;
private String username;
private String password;
private String status;
private final String JSONformat = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email=email;
}
public int getContact() {
return contact;
}
public void setContact (int contact) {
this.contact=contact;
}
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 String getStatus() {
return status;
}
public void setStatus(String status) {
this.status=status;
}
public String toString() {
return getName()+""+getEmail()+""+getContact()+""+getUsername()+""+getPassword()+""+getStatus();
}
public String fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setName(json.getString("name"));
setEmail(json.getString("email"));
setContact(json.getInt("contact"));
setUsername(json.getString("username"));
setPassword(json.getString("password"));
setStatus(json.getString("status"));
}
catch (JSONException e) {
e.printStackTrace();
}
return JSONformat;
}
TextField UserName = null;
TextField Password = null;
Form authForm, mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;
public Login() {
myDisplay = Display.getDisplay(this);
UserName = new TextField("Username", "", 10, TextField.ANY);
Password = new TextField("Password", "", 10, TextField.ANY);
authForm = new Form("Identification");
mainscreen = new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Password);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) {
if ((c == okCommand) && (d == authForm)) {
if (UserName.getString().equals("") || Password.getString().equals("")) {
alert = new Alert("Error", "You should enter Username and Password", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else {
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(), Password.getString());
}
}
if ((c == backCommand) && (d == mainscreen)) {
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm)) {
notifyDestroyed();
}
}
public void login(String UserName, String PassWord) {
HttpConnection connection = null;
DataInputStream in = null;
String base = "http://sunday-tech.com/chunghua/api/login.php";
String url = base + "?username=" + UserName + "&password=" + PassWord;
OutputStream out = null;
try
{
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Length", "" + (UserName.length() + PassWord.length()));
connection.setRequestProperty("UserName", UserName);
connection.setRequestProperty("PassWord", PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while ((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
mainscreen.append(fromJSON(b.toString()));
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (connection != null) {
connection.close();
}
}
catch (Exception x) {
}
myDisplay.setCurrent(mainscreen);
}
}
Change your setter methods to also change the TextField values. For example
public void setUsername (String username) {
this.username = username;
this.UserName.setString(username);
}
public class CreateNewUser {
public String fullName;
public int age;
public String school;
public String username;
public String password;
File file = new File("users.txt");
public void setFullName(String n) {
this.fullName = n;
}
public void setAge(int a) {
this.age = a;
}
public void setUsername(String u) {
this.username = u;
}
public void setPassword(String p) {
this.password = p;
}
public String getFullName() {
return fullName;
}
public String getSchool() {
return school;
}
public int getAge() {
return age;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
//write all info on to .txt
public void writeToInfoFile(String u, String p, String s, int a) {
}
//write username & password to a sepereate file (users.txt)
public void writeToUsersFile(String u, String p) {
try{
PrintWriter output = new PrintWriter(file);
//if username exists throw exception
output.println(username + " " + password);
output.close();
} catch (IOException ex){
System.out.println("ERROR: file not found.");
}
}
}
public class CreateNewUserTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
CreateNewUser raul = new CreateNewUser();
CreateNewUser jake = new CreateNewUser();
String username, password;
String uni;
int age;
//Raul
System.out.printf("\tHello! Welcome to Ponder\t");
System.out.println();
System.out.print("Enter desired username: ");
username = in.nextLine();
raul.setUsername(username);
System.out.println();
System.out.print("Enter desired password: ");
password = in.nextLine();
raul.setPassword(password);
raul.writeToUsersFile(username, password);
in.close(); //close scanner
}
}
everytime I add a new username and passoword it replace the existing username and password. I want it to add the new username and password on a new line.
In the function writeToUsersFile, replace the following line:
PrintWriter output = new PrintWriter(file);
with
PrintWriter output new PrintWriter(new FileWriter("users.txt", true));
Also one more point, which are unrelated to your question:
Unless this is a toy application, I would recommend against writing username and password in plain text to files on disk. You don't want the passwords lying around like that on your disk. You may want to consider using some password stores (like Keychain on OS X) or Java Key Store from within Java.
The file is being overwritten, using true appends to a file instead.Try this instead:
PrintWriter output = new PrintWriter(new FileWriter(file, true));