hi im newbie in java and i try to create a login/registration by using array. but when i try to login the account that i created it always shows out the wrong login details message, am i missing something? or should i use other method to do the validation check other than using array? tq
here’s my code
import java.util.Scanner;
public class sample {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number of account u want to register");
int n=s.nextInt();
int regid[]=new int[n];
int regpass[]=new int[n];
for(int i=0;i<n;i++){//for reading id and pass
System.out.println("enter your favorite user id: ");
regid[i]=s.nextInt();
System.out.println("enter your password: ");
regpass[i]=s.nextInt();
s.nextLine();
}
System.out.printf("%-2s %-20sn", "user id", "password");
for(int i=0;i<n;i++){//for printing all registerted account
System.out.printf("%7d %-20s n", regid[i], regpass[i]);
}
System.out.printf("==========================n");
System.out.printf("==========LOGIN===========");
System.out.printf("==========================n");
System.out.printf("enter your userid");
String id = s.nextLine();
System.out.printf("enter your password");
String pass = s.nextLine();
//user validation
if(id.equals(regid) && pass.equals(regpass)) {
System.out.printf("welcome");
}else {
System.out.printf("wrong id or password");
}
}
}
Advertisement
Answer
I changed the code to get the desired result :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number of account u want to register");
int n=s.nextInt();
int regid[]=new int[n];
int regpass[]=new int[n];
for(int i=0;i<n;i++){//for reading id and pass
System.out.println("enter your favorite user id: ");
regid[i]=s.nextInt();
System.out.println("enter your password: ");
regpass[i]=s.nextInt();
s.nextLine();
}
System.out.printf("%-2s %-20sn", "user id", "password");
for(int i=0;i<n;i++){//for printing all registerted account
System.out.printf("%7d %-20s n", regid[i], regpass[i]);
}
System.out.printf("==========================n");
System.out.printf("==========LOGIN===========");
System.out.printf("==========================n");
System.out.printf("enter your userid");
String id = s.nextLine();
System.out.printf("enter your password");
String pass = s.nextLine();
//user validation
boolean logged = false;
for (int i = 0; i < n; i++) {
if(Integer.parseInt(id) == regid[i] && Integer.parseInt(pass) == regpass[i]) {
System.out.println("welcome");
logged = true;
break;
}
}
if(!logged)
System.out.println("wrong id or password");
}