So I have made a random password Generator as homework for my Uni class, However i do have an issue with code breaking and exiting with "java.lang.IndexOutOfBoundsException : Invalid array range: 0 to 0" message once it gets to first itteration of loop in method that should generate my password. This is an updated version of code that implements scanner as option for user tu input his/her desired password lenght from keyboard. In previos version when password length was hardcoded as a set number, it worked allright. If there is anny mistake in question format or maybe the code looks ugly or whatever, I do apoligize beforehand as my coding skills are at the very bottom in my current stage.
package com.company;
import java.util.*;
public class Main {
static final String AllTheCharactersOnMyKeyBoard = "~!@#$%^&*()_+`1234567890-=QWERTYUIOP{}qwertyuiop[]ASDFGHJKL:|asdfghjkl;'|ZXCVBNM<>?zxcvbnm,./'";
static int PasswordLength;
static List<Character> ListOfCharsOnMyKBoard = convertsTheStringToCharacterList(AllTheCharactersOnMyKeyBoard);
static char[] GeneratedCharacters= new char[PasswordLength];
public static void main(String[] args) {
Scanner PassLengthScanner=new Scanner(System.in);
System.out.println("How many Symbols You wish the new password to contain?");
PasswordLength= PassLengthScanner.nextInt();
GeneratedPassword();
System.out.println(ListOfCharsOnMyKBoard);
System.out.println("\n\n\nYour Password is:");
System.out.println(GeneratedCharacters);
}
public static List<Character> convertsTheStringToCharacterList(String AllTheCharactersOnMyKeyBoard){
List<Character> MyKeyBoardCharacterList= new ArrayList<>();
for (char CHARACTER : AllTheCharactersOnMyKeyBoard.toCharArray()){
MyKeyBoardCharacterList.add(CHARACTER);
}
return MyKeyBoardCharacterList;
}
public static void GeneratedPassword(){
Random TheGenerator= new Random();
for (int i=0; i<PasswordLength; i++) {
char RandomOne = ListOfCharsOnMyKBoard.get(TheGenerator.nextInt(ListOfCharsOnMyKBoard.size()));
GeneratedCharacters[i]=(RandomOne);
}
}
}
The stacktrace is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.company.Main.GeneratedPassword(Main.java:31)
at com.company.Main.main(Main.java:15)
Line 31 of the program is this line:
GeneratedCharacters[i]=(RandomOne);