so what im doing is creating a program that reads in 2 text files, 1 is a plain text file the other is an encrypted version of the text file.
I set the String (for every line) to uppercase and i take the char of the String index 0-65 thats where i get my position in the array.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadIn {
public void fileReader(){
try{
Scanner inFile1 = new Scanner(new File("plaintext.txt"));
//Scanner inFile2 = new Scanner(new File("ciphertext.txt"));
int lol[] = new int[27];
while(inFile1.hasNextLine()){
String base = inFile1.nextLine();
base.toUpperCase();
String placeHolder = base;
for(int i=0;i<base.length();i++){
if(placeHolder.charAt(0)==' '){}
else if(base.charAt(0)=='.'){}else if(base.charAt(0)==','){}
else if(base.charAt(0)=='"'){}else if(base.charAt(0)==':'){}
else if(base.charAt(0)=='-'){}else if(base.charAt(0)=='?'){}
else if(base.charAt(0)=='!'){}else{lol[(base.charAt(0)-65)]++;}
placeHolder = placeHolder.substring(1);
}
}
for(int j=0;j<lol.length;j++){
System.out.println(lol[j]);
//To show what is inside the Index.
}
}catch(FileNotFoundException e){
System.out.println("File is not in the correct directory!");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array Index is to small!!");
}
}
}
This is the output i get when i set the array size to 60
142 119 0 0 0 62 60 0 682 0 0 179 24 232 0 62 0 0 0 184 0 0 440 0 63 0 0 0 0 0 0 0 471 182 215 94 60 409 0 242 174 15 30 62 273 79 405 189 0 195 472 673 101 62 324 0 124 0 0 0
The question is, when I run the program, why is my array to small. If all letters are capitalized, then subtracting 65 from a char such as ‘A’ should be 0 and therefor add 1 to index [0] in the array.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
update
OK so i set the string to capitalize it self by “base = base = base.toUpperCase();”
This worked flawlessly except that my array has to be set at 91 to compensate for the Z (90) in ascii
when i try to go to the index point of the array to add i use [(base.charAt(0)-65)]++
but it throws ArrayIndexOutOfBoundsException -21
Your
basestill contains lowercase characters, as you’re not using the return value oftoUpperCase(). This is confirmed by your test data: your output spans the ASCII range from 65 (A) to 122 (z), counting 58 different character codes.Strings in Java are immutable, their value does not change after they are constructed. Therefore,
base.toUpperCase()returns a new string and does not modify the originalbasestring. You want to replacebaseby its capitalized version, therefore you should override its value so it points to the returned string: