Reputation: 63
I'm struggling here. My program is about a simple sign in and log in using array. Now, whenever I want to sign in, I want all the usernames and passwords to be displayed whenever I want to check if all the accounts I created are successfully collected in an array. Now whenever I want to display all the accounts, usernames aren't displaying, just the passwords. Here is my code:
package login;
import java.util.*;
import static java.lang.System.out;
public class login {
public static void main(String [] args) {
String user [] = new String [100];
String pass [] = new String [100];
int sign=0;
boolean again=true, logAgain=true;
Scanner scan = new Scanner (System.in);
while(again) {
out.println("[1]Sign-up\n[2]Log-in\n[3]Display Account?\n[4]Exit");
out.print("Select: ");
int a=scan.nextInt();
if (a==1) {
again=false;
sign++;
out.print("Username: ");
user[sign]=scan.nextLine();
scan.nextLine();
out.print("Password: ");
pass[sign]=scan.nextLine();
out.println("Log in now? [Y/N] : ");
String b=scan.next();
if(b.equals("Y")||b.equals("y")) {
again=true;
} else {
again=false;
System.exit(0);
}
} else if(a==2){
again=false;
logAgain=true;
while(logAgain) {
out.print("Username: ");
String userU=scan.nextLine();
scan.nextLine();
out.print("Password: ");
String userP=scan.nextLine();
if (userU.equals(user[sign])&&userP.equals(pass[sign])) {
out.println("You're logged in!");
logAgain=false;
out.println("Back to menu? [Y/N] : ");
String c=scan.next();
if (c.equals("Y")||c.equals("y")) {
again=true;
} else {
System.exit(0);
}
}else if (!userU.equals(user[sign])&&userP.equals(pass[sign])) {
out.println("Invalid username or Password!");
logAgain=true;
}else {
again=true;
logAgain=false;
out.println("Please register first!");
}
}
} else if (a==3) {
again=false;
if (sign<1) {
out.println("\nNo account to display!\nPlease sign-up first.\n");
again=true;
} else {
System.out.println("");
System.out.printf("%-15s%10s\n","Username","Passwords");
for (int i = 1; i <=sign; i++)
System.out.printf("%-15s%10s\n",user[i],pass[i]);
System.out.println("");
out.println("Back to menu? [Y/N] : ");
String c=scan.next();
if (c.equals("Y")||c.equals("y")) {
again=true;
} else {
System.exit(0);
}
}
} else if(a==4) {
again=false;
System.exit(0);
} else {
}
}
}
}
And my output goes like this:
[1]Sign-up
[2]Log-in
[3]Display Account?
[4]Exit
Select: 3
Username Passwords
Password
pass
evohohivr
Back to menu? [Y/N] :
Thank you in advance.
Upvotes: 1
Views: 58
Reputation: 972
Your discarding the wrong Scanner
input. It should read like this:
if (a==1) {
again=false;
sign++;
out.print("Username: ");
scan.nextLine(); // This was the wrong order
user[sign]=scan.nextLine();
out.print("Password: ");
pass[sign]=scan.nextLine();
out.println("Log in now? [Y/N] : ");
String b=scan.next();
if(b.equals("Y")||b.equals("y")) {
again=true;
} else {
again=false;
System.exit(0);
}
}
Upvotes: 1