Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JOptionPane;
- import java.io.*;
- import java.util.*;
- public class user
- {
- public static ArrayList<ArrayList<String>> users;
- public static void main(String[] args) throws IOException
- {
- String[] details = usernameValidation();
- if(details[0]!= "") //Empty string is assigned to the first index if the username
- { //and password are invalid in usernameValidation method
- String username = details[0];
- int userScore = Integer.valueOf(details[1]); //Gave the details simple variable names for ease of use
- }
- }
- public static String[] usernameValidation() throws IOException
- {
- boolean validInput = false;
- int chances = 3;
- String username = new String();
- String password = new String();
- String userScore = new String();
- File inputFile = new File("users.txt");
- users = new ArrayList<ArrayList<String>>();
- users.add(new ArrayList<String>());
- users.add(new ArrayList<String>());
- users.add(new ArrayList<String>()); //set up my array list for the user details
- String fileElements[];
- Scanner in = new Scanner(inputFile); //makes connection between scanner object and the file
- while(in.hasNext()) //for each row in the list, loop
- {
- fileElements = (in.nextLine()).split(","); //puts the details into an array by using a comma to split the details
- users.get(0).add(fileElements[0]); //the users.txt file is in the format 'username','password',score
- users.get(1).add(fileElements[1]);
- users.get(2).add((fileElements[2])); //adds each seperate users details into the array list for ease of use
- }
- in.close(); //ends association between scanner and file
- while(!validInput && chances!=0)
- {
- username = JOptionPane.showInputDialog(null,"Enter your username you have only " + chances + " chance(s) remaining");
- password = JOptionPane.showInputDialog(null,"Enter your password"); //Allows user to enter name and password
- for(int j = 0;j<users.get(0).size();j++) //and stores them in variables
- {
- //goes through each element in the list
- if(username.equals(users.get(0).get(j)) && password.equals(users.get(1).get(j))) //compares details entered to each element
- { //in the array lists
- validInput = true;
- JOptionPane.showMessageDialog(null,"Login details are valid");
- userScore = users.get(2).get(j); //Since we have username, we must access score when details are at correct index
- }
- }
- if(!validInput)
- {
- chances--; //decrement chances if the details entered are incorrect
- JOptionPane.showMessageDialog(null,"Login details entered were invalid");
- }
- }
- if(validInput)
- {
- String[] details = {username,userScore};
- return details; //returns the details required
- }
- else
- {
- String[] details = {"",""};
- return details; //If the input is incorrect, return these values
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement