I have this code:
for(int i=0;i<numRows;i++)
{
String Usernames = rs.getString("Username");
String Password = rs.getString("Password");
String getAcc = rs.getString("UserType");
rs.next();
if(Usernames.contains(UsernameIn.trim())&&Password.contains(PasswordIn.trim()))
{
if(getAcc.trim().equals("admin"))
{
clear();
AdminUser.UTypeAdmin(args, UsernameIn, rs, dbTable(), path);
}
if(getAcc.trim().equals("standard"))
{
clear();
StandardUser.UTypeStandard(args, UsernameIn, rs, dbTable(),path);
}
}
if(!Usernames.contains(UsernameIn.trim())&&!Password.contains(PasswordIn.trim()))
{
System.out.println("Invalid Credentials Entered");
Thread.sleep(2000);
clearandreset(args);
}
}
Ideally, the program would compare the user's input to the resultset and determine if the inputs match. When a correct user enters their credentials, the application runs fine. Eventually the application resets as expected, but when another valid user is entered, the application displays Invalid Credentials Entered, thus breaking the application. Has anyone got a solution for this?
first, you should move "invalid credentials" code outside the loop. Otherwise it will work only if credentials matches the first row.
second, check that you are not reusing same result set instance twice
for(int i=0;i<numRows;i++)
{
String Usernames = rs.getString("Username");
String Password = rs.getString("Password");
String getAcc = rs.getString("UserType");
rs.next();
if(Usernames.contains(UsernameIn.trim())&&Password.contains(PasswordIn.trim()))
{
if(getAcc.trim().equals("admin")) {
clear();
AdminUser.UTypeAdmin(args, UsernameIn, rs, dbTable(), path);
}
if(getAcc.trim().equals("standard")) {
clear();
StandardUser.UTypeStandard(args, UsernameIn, rs, dbTable(),path);
}
}
}
// We have traversed all rows but not found matching user
System.out.println("Invalid Credentials Entered");
Thread.sleep(2000);
clearandreset(args);
Related
I have been working on this program and have recently came to an error using a static method.
I don't normally use static methods but they are in the requirements.
So i have a static method VerifyUserNameAndPassWord which takes an input of a list of users and a user name and password and compares it to the ones stored in the object to see if the details are correct.
Unfortunately with this method it only ever recognized "User1" (Thefirst object) and any time i try to put in user2's username and password it always throws the illegal argument error i put in.
User 2 is stored in the array list of course.
This is my main method:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your user name");
String userName = scanner.nextLine();
System.out.println("Enter your password name");
String passWord = scanner.nextLine();
if(User.verifyLoginByUsernameAndPassword(userList, userName, passWord)== true)
{
do something..
}
And this is the static method:
public static boolean verifyLoginByUsernameAndPassword(ArrayList<User> user, String username, String password)
{
boolean check = false;
for(User s: user)
{
if(username.equals(s.getUserName()) && password.equals(s.getPassWord()))
{
check = true;
break;
}
else
{
check = false;
throw new IllegalArgumentException("Username and password are incorrect ");
}
}
return check;
}
Change your method implementation. Check the entire list then throw exception if username and passwords not matched.
public static boolean verifyLoginByUsernameAndPassword(ArrayList<User> user, String username, String password) {
for(User s: user) {
if(username.equals(s.getUserName()) && password.equals(s.getPassWord())) {
return true;
}
}
throw new IllegalArgumentException("Username and password are incorrect ");
}
I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.
I have an addUser() method that adds a new user to the <FacebookUser> users ArrayList.
void addUser() {
String username;
String password;
String passwordHint;
System.out.println("Please type in your desired username:");
username = input.nextLine();
if (users.toString().contains(username)) {
System.out.println("Username already exists!");
} else {
System.out.println("Please type in your desired password:");
password = input.nextLine();
System.out.println("Please type in your password hint:");
passwordHint = input.nextLine();
FacebookUser newUser = new FacebookUser(username, password);
newUser.setPasswordHint(passwordHint);
users.add(newUser);
}
}
I'm now trying to make a deleteUser() method and I got stuck at this part. I'm supposed to compare the given password with the the Facebook User's password that is associated with the given username. If the passwords match, I should remove the FacebookUser object from the users ArrayList.
void deleteUser() {
String username;
String password;
System.out.println("Please type in your username:");
username = input.nextLine();
if (users.toString().contains(username)) {
System.out.println("Please type in your password:");
password = input.nextLine();
} else {
System.out.println("Username doesn't exist!");
}
}
Any help is greatly appreciated!
I'm supposed to compare the given password with the Facebook User's password that is associated with the given username.
Keeping my solution simple. Your first step is get the targeted user object from the list.
User target = null;
for(User u : users)
if(u.getUserName().equals(enteredUserName)) //Assuming all usernames are unique
target = u;
Next, check whether given password matches.
if(target.getPassword().equals(enteredPassword)) //if password matches
users.remove(target); //delete user from list
I assume users is a List.
Here's a good method to do it if the getters are correct.
You just find the right index of username and then check the password.
for (int i = 0 ; i < users.length() ; i++){
if (users.get(i).getName().equals(username)){
if (users.get(i).getPassword().equals(password)) System.out.println("Deleted");
else System.out.println("Password incorrect !");
break;
}
}
EDIT : Here I just printed out the actions to be crystal clear but in practice, the best is to store the index and delete the index once you've breaken out the loop
This one has been bugging me for a little bit and I can't for the life of me figure it out:
I have to get my application to collect input from the user as a means of logging in to a database. My issue is, only the first user is actually allowed in according to the code. What am I doing wrong?
CODE
for(int i=0;i<numRows;i++)
{
String Usernames = rs.getString("Username");
String Password = rs.getString("Password");
String getAcc = rs.getString("UserType");
rs.next();
if(Usernames.trim().equals(UsernameIn)&&Password.trim().equals(PasswordIn))
{
start.writeToFile("ConToDatabase Class|Username: "+UsernameIn+" and Password: "+PasswordIn+" Accepted");
if(getAcc.trim().equals("admin"))
{
start.writeToFile("ConToDatabase Class|Authenticated user identified as \"admin\", Entering AdminUser Class|UTypeAdmin Method");
clear();
AdminUser.UTypeAdmin(args, UsernameIn, rs, dbTable(), path);
}
if(getAcc.trim().equals("standard"))
{
start.writeToFile("ConToDatabase Class|Authenticated user identified as \"standard\", Entering StandardUser Class|UTypeStandard Method");
clear();
StandardUser.UTypeStandard(args, UsernameIn, rs, dbTable(),path);
}
}
else
{
start.writeToFile("ConToDatabase Class|User invalid, reset application");
System.out.println("Invalid User, Resetting...");
Thread.sleep(2000);
ConToDatabase.clearandreset(args);
}
}
I think that the problem is the code in your ELSE block.
You want to test all the users before say that the user is invalid.
With the first user you dont have that problem because you only arrived to the IF block code, but with all the other users you gonna pass by the ELSE block at least once.
You can do something like this:
boolean founded = false;
for(int i=0;i<numRows;i++)
{
String Usernames = rs.getString("Username");
String Password = rs.getString("Password");
String getAcc = rs.getString("UserType");
rs.next();
if(Usernames.trim().equals(UsernameIn)&&Password.trim().equals(PasswordIn))
{
founded = true;
start.writeToFile("ConToDatabase Class|Username: "+UsernameIn+" and Password: "+PasswordIn+" Accepted");
if(getAcc.trim().equals("admin"))
{
start.writeToFile("ConToDatabase Class|Authenticated user identified as \"admin\", Entering AdminUser Class|UTypeAdmin Method");
clear();
AdminUser.UTypeAdmin(args, UsernameIn, rs, dbTable(), path);
}
if(getAcc.trim().equals("standard"))
{
start.writeToFile("ConToDatabase Class|Authenticated user identified as \"standard\", Entering StandardUser Class|UTypeStandard Method");
clear();
StandardUser.UTypeStandard(args, UsernameIn, rs, dbTable(),path);
}
}
}
if(!founded)
{
start.writeToFile("ConToDatabase Class|User invalid, reset application");
System.out.println("Invalid User, Resetting...");
Thread.sleep(2000);
ConToDatabase.clearandreset(args);
}
You want to pay attention at the comments in your answer too.