'Entering an only alphanumeric string runs into a java.lang.IndexOutOfBoundsException but works like intended otherwise

I get an error when I try to type a password consisting only alphanumeric characters but loops the way I intended if I type symbols. This is my first time trying to make a program that writes and reads a file and I'm still stuck here. I tried to paste the entire code to a different class but still runs into the same situation. I have no clue what caused this error. The IDE I'm currently using is Eclipse.

The full error is:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) 
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)   
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) 
at java.base/java.util.Objects.checkIndex(Objects.java:359) 
at java.base/java.util.ArrayList.get(ArrayList.java:427)    
 TaskPerf6.main(TaskPerf6.java:66)

Source:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class TaskPerf6 {
    
     public static boolean isAlphaNumeric(String username) {
            return username != null && username.matches("^[a-zA-Z0-9]*$");
        }
     
     public static boolean isAlphaNumeric1(String password) {
            return password != null && password.matches("^[a-zA-Z0-9]*$");
        }

    public static void main(String[] args) throws IOException {     
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Type L to log-in or R to register.");
        String choice = scan.nextLine();
        
        File file = new File("records.txt");
        FileWriter writer = new FileWriter(file);
        
        //Register
        
        if (choice.compareToIgnoreCase("R") == 0) {         
            System.out.println("Registration:");
            while(true) {
                try {
                    System.out.println("Write your username (Alphanumeric Characters Only):");
                    String username = scan.nextLine();
            
                    if (isAlphaNumeric(username)==true) break;
        
                    writer.write(username + "\n");                  
                    writer.close();
                }
                catch (java.lang.IndexOutOfBoundsException e) {
                    System.out.println("a");
                }   
                catch (java.io.IOException e) {
                    System.out.println("");
                }
            }
            while(true) {
                try {
                    System.out.println("Write your password (Alphanumeric Characters Only):");
                    String password = scan.nextLine();
                    
                    if (isAlphaNumeric1(password)==true) break;
                    
                    writer.write(password + "\n");
                    writer.close();
                }
                catch (java.lang.IndexOutOfBoundsException e) {
                    System.out.println("a");
                }   
                catch (java.io.IOException e) {
                    System.out.println("");
                }
            }
            
        String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
        }
    }
}


Solution 1:[1]

You do not need two of the same methods; delete one of the isAlphaNumeric methods.

public static boolean isAlphaNumeric(String word) {
        return word != null && word.matches("^[a-zA-Z0-9]*$");
}

Your problem is here:

String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);

you are attempting to retrieve the second line of this file from the .get(1), when you have not wrote anything to the file.

The reason why you are not writing to a file is because you are using break whenever the username and password matches your regex pattern.

if (isAlphaNumeric(username)==true) break;

writer.write(username + "\n");                  
writer.close();

which will take you out of the while loop before you can write to the file.

You should practice breaking up your code for reusability. Very helpful: here is my solution for your task.

public class TaskPerf6 {
    
    static String fileName = "records.txt";
    static File file = new File(fileName);
    static Scanner scan = new Scanner(System.in);

    static final String REGISTER = "R";
    static final String LOGIN = "L";

    public static void main(String[] args){     
        
        System.out.println("Type L to log-in or R to register.");
        String choice = scan.nextLine();
        
        switch(choice.toUpperCase()) {
            case REGISTER:
                register();
                break;
            case LOGIN:
                login();
                break;
        }

        String line1 = getLineItem(0);
        System.out.println(line1);

    }

    private static void login() {
        // TODO
    }

    private static void register() {
        while(true) {
            System.out.println("Write your username (Alphanumeric Characters Only):");
            String username = scan.nextLine();
            if (processed(username)) 
                break;
        }
        while(true) {
            System.out.println("Write your password (Alphanumeric Characters Only):");
            String password = scan.nextLine();
            if (processed(password)) 
                break;
        }
    }
    
    private static boolean processed(String word) {
        boolean success = true;
        if (isAlphaNumeric(word)) {
            if (!writeToFile(word)) {
                System.out.println("Was unable to write to file");
                success = false;
            }        
        } else {
            System.out.println("Was not alphanumeric, try again");
            success = false;
        }
        return success;
    }
    
    private static boolean isAlphaNumeric(String word) {
        return word != null && word.matches("^[a-zA-Z0-9]*$");
    }
 
    private static boolean writeToFile(String word ) {
        boolean success = true;
        try {
            FileWriter writer = new FileWriter(file);
            writer.write(word + "\n");                  
            writer.close();
        } catch (IndexOutOfBoundsException | IOException e) {
            success = false;
        }
        return success;
    }
    
    private static String getLineItem(int i) {
        String item = "";
        try {
            item = Files.readAllLines(Paths.get(fileName)).get(i);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}

Solution 2:[2]

first change to be done might be not closing writer in the first loop for username but in second loop for password.

            while(true) {
            try {
                System.out.println("Write your username (Alphanumeric Characters Only):");
                String username = scan.nextLine();

                if (isAlphaNumeric(username)==true){
                    System.out.println("username correct");
                    writer.write(username+"\n");
                    break;}

            } catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
              catch (java.io.IOException e) {System.out.println("");}
        }

            while(true) {
            try {
                System.out.println("Write your password (Alphanumeric Characters Only):");
                String password = scan.nextLine();

                if (isAlphaNumeric1(password)==true){
                    System.out.println("pass correct");
                    writer.write(password);
                    writer.close();
                    break;
                }
            }
            catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
            catch (java.io.IOException e) {System.out.println("");}
        }

Solution 3:[3]

When record.txt cannot be found and you try to get index 1 that's why you're getting the index out of bound exception. Please use the following if check:

String line1;
if(!Files.readAllLines(Paths.get("records.txt")).isEmpty())
   line1 = Files.readAllLines(Paths.get("records.txt")).get(1);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Abdul Wasey