0

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

4

1 に答える 1

0

baseの戻り値を使用していないため、まだ小文字が含まれていますtoUpperCase()。これは、テスト データによって確認されます。出力は ASCII 範囲 65 ( A) から 122 ( z) にまたがり、58 の異なる文字コードを数えます。

Java の文字列は不変であり、その値は構築後に変更されません。したがって、新しい文字列base.toUpperCase()を返し、元の文字列を変更しません。大文字のバージョンに置き換えたいので、返された文字列を指すように値をオーバーライドする必要があります。basebase

base = base.toUpperCase();
于 2013-02-10T23:26:27.640 に答える