My idea was, like, to put read bytes to an array list. Then take the first element to memory variable, and then iterate through the whole array to count repeated times.
And after iterating, when repeated counter has value 1. I wanted to assign value from variable "memory" to “not Repeated list”, and reset counter to take another element from the working list.
But like you see, my first two element go well, and the third one go fail. It threw out an exception.
default: [49, 49, 51, 49, 49, 52, 49, 49]
external InMemory: 49(index 0)
internal loop: 49?49 is repeat 1
internal loop: 49?49 is repeat 2
internal loop: 49?49 is repeat 3
internal loop: 49?49 is repeat 4
internal loop: 49?49 is repeat 5
internal loop: 49?49 is repeat 6
external InMemory: 49(index 1)
internal loop: 49?49 is repeat 1
internal loop: 49?49 is repeat 2
internal loop: 49?49 is repeat 3
internal loop: 49?49 is repeat 4
internal loop: 49?49 is repeat 5
internal loop: 49?49 is repeat 6
external InMemory: 51(index 2)
internal loop: 51?51 is repeat 1
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at pl.codegym.task.task18.task1804.Solution.main(Solution.java:56)
Process finished with exit code 1
package pl.codegym.task.task18.task1804;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/*
Najrzadziej występujące bajty
*/
public class Solution {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// String fileName = scanner.nextLine();
String fileName = "C:\\Users\\PC\\Desktop\\CodeGym\\CodeGymTasks\\2.JavaCore\\src\\pl\\codegym\\task\\task18\\task1804\\readFile.txt";
FileInputStream myFileInput = new FileInputStream(fileName);
ArrayList<Integer> byteTable = new ArrayList<>();
while (myFileInput.available() > 0) {
byteTable.add(myFileInput.read());
}
myFileInput.close();
// test print
System.out.println("default: " + byteTable); // test print
// System.out.println("table size: " + byteTable.size()); // test print
//
//Collections.sort(byteTable);
// System.out.println("sorted: " + byteTable); // test print
ArrayList<Integer> notRepeat = new ArrayList<>();
int i;
int j;
int memory = 0;
int counter = 0;
for (i = 0; i <= byteTable.size()-1 ; i++) {
memory = byteTable.get(i);
System.out.println("\nexternal InMemory: " + memory + "(index " + i + ")\n"); // test print
for (j = 0; j <= byteTable.size()-1 ; j++) {
if(memory == byteTable.get(j)) {
counter++;
System.out.println("internal loop: " + memory + "?" + byteTable.get(j) + " is repeat " + counter); // test print
}
}
if(counter == 1) {
notRepeat.add(memory);
System.out.println(memory + "?" + byteTable.get(j) + "not repeat yes"); // test print
}
//reset counter
counter = 0;
}
System.out.println("\nNot repated list: " + notRepeat); // test print
}
}