JAVA Question: Index 130 out of bounds for length 130 [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am running the following code and I keep getting the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130
at Datachange.init(Datachange.java:55)
at Datachange.main(Datachange.java:38)
I am trying to read a file and manipulated into an output and its seems that its not reading the file well.
'
import java.io.*;
public class Datachange
{
public class variables
{
private char [] body;
private int ID;
private int population;
private int populationchilds;
private int populationchildspoverty;
private double populationchildpovertypercent;
variables(char [] input)
{
body = input;
char[] stateID = java.util.Arrays.copyOfRange(body,0,2);
ID = Integer.parseInt(new String(stateID).trim());
char[] totalpopulation = java.util.Arrays.copyOfRange(body,83,90);
population = Integer.parseInt(new String(totalpopulation).trim());
char [] childpopulation = java.util.Arrays.copyOfRange(body,92,99);
populationchilds = Integer.parseInt(new String(childpopulation).trim());
char [] povertychilds = java.util.Arrays.copyOfRange(body,101,108);
populationchildspoverty = Integer.parseInt(new String(povertychilds).trim());
}
}
public static void main(String[] args)
{
Datachange DS = new Datachange();
DS.init();
}
public void init()
{
variables dataframe[] = new variables[13286];
try (FileReader inputDataframe = new FileReader("file.txt"))
{
int c;
int i = 0;
int j = 0;
char variableinput [] = new char[130];
while((c = inputDataframe.read())!=-1)
{
variableinput[i] = (char) c;
i++;
if(c==10)
{
dataframe[j] = new variables(variableinput);
j++;
i = 0;
}
}
}
catch(IOException except)
{
System.out.println("There is Input/Output Error:" + except.getMessage());
}
this.newdata(dataframe);
}
public variables[] newdata(variables[] dataset)
{
variables[] newdata=new variables[57];
try (BufferedWriter outData = new BufferedWriter(new
FileWriter("manipulatedfile.txt")))
{
int stateID = 1; //First ID
int statePop= 0;
int stateChdPop=0;
int stateChdPovertyPop=0;
for(int i=0;i<dataset.length;i++)
{
if (dataset[i].ID == stateID)
{
statePop += dataset[i].population;
stateChdPop += dataset[i].populationchilds;
stateChdPovertyPop += dataset[i].populationchildspoverty;
}
else
{
double stateChdPovertyPopPercent=0;
if (stateChdPop != 0)
{
stateChdPovertyPopPercent = (double)
stateChdPovertyPop/stateChdPop * 100;
int z = 12;
}
else
{
stateChdPovertyPopPercent = 0;
}
outData.append(stateID + "\t" + statePop + "\t" +
stateChdPop + "\t" + stateChdPovertyPop+
"\t" + stateChdPovertyPopPercent + "\n");
statePop = 0;
stateChdPop = 0;
stateChdPovertyPop = 0;
i--;
stateID++;
}
}
}
catch(IOException except)
{
System.out.println("I/O Error:" + except.getMessage());
}
int x = 12;
return newdata;
}
}
'

It is reading the file just fine, otherwise it would throw an IOException instead of an ArrayIndexOutOfBoundsException.
From the Oracle Documentation about ArrayIndexOutOfBoundsException:
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
That happens in your init() method if I am not mistaken. You have an array that has a limit of 130 and trying to get the element at index 130+ (because arrays start counting at 0) will give you that exception.
variableinput[130] will throw it.

Related

Java Runtime Issue: ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130 [duplicate]

This question already has answers here:
JAVA Question: Index 130 out of bounds for length 130 [duplicate]
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am running the following code and I keep getting the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 130 at Datachange.init(Datachange.java:55) at Datachange.main(Datachange.java:38)
I am trying to read a file and manipulated into an output and its seems that its not reading the file well. '
import java.io.*;
public class Datachange
{
public class variables
{
private char [] body;
private int ID;
private int population;
private int populationchilds;
private int populationchildspoverty;
private double populationchildpovertypercent;
variables(char [] input)
{
body = input;
char[] stateID = java.util.Arrays.copyOfRange(body,0,2);
ID = Integer.parseInt(new String(stateID).trim());
char[] totalpopulation = java.util.Arrays.copyOfRange(body,83,90);
population = Integer.parseInt(new String(totalpopulation).trim());
char [] childpopulation = java.util.Arrays.copyOfRange(body,92,99);
populationchilds = Integer.parseInt(new String(childpopulation).trim());
char [] povertychilds = java.util.Arrays.copyOfRange(body,101,108);
populationchildspoverty = Integer.parseInt(new String(povertychilds).trim());
}
}
public static void main(String[] args)
{
Datachange DS = new Datachange();
DS.init();
}
public void init()
{
variables dataframe[] = new variables[13486];
try (FileReader inputDataframe = new FileReader("SmallAreaIncomePovertyEstData.txt"))
{
int c;
int i = 0;
int j = 0;
char variableinput [] = new char[130];
while((c = inputDataframe.read())!=-1)
{
variableinput[i] = (char) c;
i++;
if(c==10)
{
dataframe[j] = new variables(variableinput);
j++;
i = 0;
}
}
}
catch(IOException except)
{
System.out.println("There is Input/Output Error:" + except.getMessage());
}
this.newdata(dataframe);
}
public variables[] newdata(variables[] dataset)
{
variables[] newdata=new variables[57];
try (BufferedWriter outData = new BufferedWriter(new
FileWriter("SmallAreaIncomePovertyEstDatanew.txt")))
{
int stateID = 1; //First ID
int statePop= 0;
int stateChdPop=0;
int stateChdPovertyPop=0;
for(int i=0;i<dataset.length;i++)
{
if (dataset[i].ID == stateID)
{
statePop += dataset[i].population;
stateChdPop += dataset[i].populationchilds;
stateChdPovertyPop += dataset[i].populationchildspoverty;
}
else
{
double stateChdPovertyPopPercent=0;
if (stateChdPop != 0)
{
stateChdPovertyPopPercent = (double)
stateChdPovertyPop/stateChdPop * 100;
int z = 12;
}
else
{
stateChdPovertyPopPercent = 0;
}
outData.append(stateID + "\t" + statePop + "\t" +
stateChdPop + "\t" + stateChdPovertyPop+
"\t" + stateChdPovertyPopPercent + "\n");
statePop = 0;
stateChdPop = 0;
stateChdPovertyPop = 0;
i--;
stateID++;
}
}
}
catch(IOException except)
{
System.out.println("I/O Error:" + except.getMessage());
}
int x = 12;
return newdata;
}
}
Welcome to SO. If its ArrayIndexOutOfBound then its not compile time issue, its runtime. I'm not sure but it seems issue can be in below code block
while((c = inputDataframe.read())!=-1)
Why I think there can be issue, is because in that while block you are incrementing pointer of variableinput without checking if pointer index is less than 130 or not, so if at anytime input has more characters than 130, then your code will fail as array has fixed size.
Solution to that can be to use List<Character> instead of char[]
Let me know if this not working for you.
Good luck!

Sorting an array using max-heap in Java

I'm working on a program which sorts an array by dividing it into smaller max-heaps and extracting the max-integer out of each one, then deleting it from the heap and running again until every heap is empty, but I can't seem to figure it out.
From where I stand the code looks good, but I don't get the results which I am looking for. My input is created randomly, and makes an array of 512 integers. Here is what it prints for one example run -
Original Array -391 176 -380 -262 -474 327 -496 214 475 -255 50 -351 179 -385 -442 -227 465 127 -293 288
Sorted Array 475 465 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327 327
n = 20 k = 2
The number of comparisons is 243
Can anyone spot what's wrong with my code? I will be really gladful.
(1) Main Program
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.IOException;
public class Project {
static final int n = 20;
static final int k = 2;
static int counter = 0;
private static Scanner scan;
public static void main(String[] args) throws IOException {
// Optional - reading from a file containing 512 integers.
InputCreator.main();
File f = new File("random.txt");
// File f = new File("increase.txt");
// File f = new File("decrease.txt");
try { scan = new Scanner(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
int [] L = new int[n];
System.out.print("Original Array ");
for (int i = 0; i < n ; i++)
{ counter++; L[i] = scan.nextInt(); System.out.print(" " + L[i]); }
Projectsort(L);
}
private static void Projectsort(int [] L) {
// int [][] Li = new int [k] [n-(n/k*(k-1))]; // The size of the rest of the integers (n-(n/k*(k-1)) will always be bigger than n/k
int [] temp = new int [n/k], extra = new int [n-(n/k)*(k-1)];
int extraIndex = 0, max, maxIndex = 0, r = 0;
ProjectMaxHeap [] Li = new ProjectMaxHeap [k];
// The following loop's time effiency is O(k) * O(N/k) = O(N)
for (int i=0; i<k-1; i++) { counter++; // copying all the integers from Array L into K-1 smaller arrays
for (int j=0; j<n/k ; j++)
{ counter++; temp [j] = L[i*(n/k)+j]; }
Li[i] = new ProjectMaxHeap (temp); }
for (int i=(n/k)*(k-1) ; i<n ; ++i) // The rest of the integers on array L
{ counter++; extra [extraIndex] = L[i]; extraIndex++; }
Li[k-1] = new ProjectMaxHeap(extra);
System.out.print("\nSorted Array ");
for (int i = n ; i > 0 ; i--) { counter++;
r = 0;
do{max = Li[r].extractMax(); r++; }while(Li[r].isEmpty() && r < k - 1);
for (int j = r; j < k; j++) // Time efficiency O(k)*O(N/k)
{ counter++;
if(!Li[j].isEmpty()) {
if (Li[j].extractMax() > max) {
counter++;
max = Li[j].extractMax();
maxIndex = j; }
}
System.out.print(max + " ");
Li[maxIndex].deleteMax(); } }
System.out.println("\nn = " + n + " k = " + k +"\nThe number of comparisons is " + counter);
}
}
(2) Max Heap Class
public class ProjectMaxHeap
{
private int [] _Heap;
private int _size;
public ProjectMaxHeap (int [] A){
_size = A.length;
_Heap = new int[A.length];
System.arraycopy(A, 0, _Heap, 0, A.length);
for (int i = _size / 2 ; i >=0 ; i--) {
Project.counter++;
maxHeapify(i); }
}
private int parent(int pos)
{ return pos / 2; }
private int leftChild(int pos)
{ return (2 * pos); }
private int rightChild(int pos)
{ return (2 * pos) + 1; }
private void swap(int fpos,int spos) {
int tmp;
tmp = _Heap[fpos];
_Heap[fpos] = _Heap[spos];
_Heap[spos] = tmp; }
private void maxHeapify (int i) {
int l = leftChild(i), r = rightChild(i), largest;
if(l < _size && _Heap[l] > _Heap[i]) {
Project.counter+=2;
largest = l; }
else largest = i;
if(r < _size && _Heap[r] > _Heap[largest]) {
largest = r;
Project.counter+=2; }
if (largest != i) {
Project.counter++;
swap(i, largest);
maxHeapify (largest); }
}
protected boolean isEmpty() { return _size == 0; }
protected void deleteMax() {
if (_size > 1) {
Project.counter++;
maxHeapify(0);
int max = _Heap[0];
_size--;
swap(0, _size);
maxHeapify(0); }
else _size = 0;
}
protected int extractMax() {
maxHeapify(0);
return _Heap[0];
}
}
(3) Input Creator
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.io.FileReader;
import java.io.BufferedReader;
public class InputCreator {
public static void main() {
randomizer();
decrease();
increase();
}
private static void randomizer() {
// The target file
File out = new File("random.txt");
FileWriter fw = null;
int n = 0;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = random.nextInt(1000)-500;
writer.write(line + "\r\n");
n++;
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void increase() {
// The target file
File out = new File("increase.txt");
FileWriter fw = null;
int n = 0;
int temp = 0;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = random.nextInt((n+1)*10);
if(line > temp) {
writer.write(line + "\r\n");
n++;
temp = line; }
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
private static void decrease() {
// The target file
File out = new File("decrease.txt");
FileWriter fw = null;
int n = 0;
int temp = 10000;
// Try block: Most stream operations may throw IO exception
try {
// Create file writer object
fw = new FileWriter(out);
// Wrap thק writer with buffered streams
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while (n < Project.n) {
// Randomize an integer and write it to the output file
line = 10000 - random.nextInt((n+1)*20);
if(line < temp) {
writer.write(line + "\r\n");
n++;
temp = line; }
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
The problem is with max = Li[0].extractMax(); You are not checking if Li[0] might be empty.
Always check preconditions and fail fast. The problem would have become immediately obvious had you started extractMax and deleteMax with
if (_size == 0) {
throw new IllegalStateException("empty heap");
}
Here's the fixed final loop:
for (int i = 0; i < n; i++) {
int maxIndex = -1; // remove these variable declarations from top of method
int max = Integer.MIN_VALUE; // it's best to confine variables to narrow scope
for (int j = 0; j < k; j++) {
if (!Li[j].isEmpty()) {
int current = Li[j].extractMax();
if (maxIndex == -1 || current > max) {
maxIndex = j;
max = current;
}
}
}
assert maxIndex != -1;
Li[maxIndex].deleteMax();
System.out.print(max + " ");
}

Fix NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
How could I get the program to output all the information? IT currently returns a NullPointException error. Thanks.
I am supposed to use the delete methods just as they are, I cannot change them, but I am sure there must be something I can do.
public class TestCandidate7
{
public static int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void printResults(Candidate[] election)
{
double percent;
System.out.println("Candidate Votes Received % of Total Votes");
for (int x = 0; x < election.length; x++)
{
percent = (double) (election[x].votes()) / getTotal(election) * 100;
System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
System.out.println();
}
}
public static void deleteByLoc(Candidate[] election,
int location)
{
if ((location > 0) && (location < election.length))
{
//move items up in the array -
for(int index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void deleteByName(Candidate[] election,
String find)
{
int location = 0;
int index;
// find location of item you want to delete
for(index = 0; index < election.length; index++)
if ((election[index] != null) && (election[index].getName().equals(find)))
{
location = index;
break;
}
else if (election[index] == null)
{
location = -1;
break;
}
if ((index != election.length) && (location >= 0))
{ //move items up in the array
for(index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[10];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
election[5] = new Candidate("Mickey Jones", 3000);
election[6] = new Candidate("Rebecca Morgan", 2000);
election[7] = new Candidate("Kathleen Turner", 8000);
election[8] = new Candidate("Tory Parker", 500);
election[9] = new Candidate("Ashton Davis", 10000);
System.out.println("Original results:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByLoc(election, 6);
System.out.println("Deleted location 6:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByName(election, "Kathleen Turner");
System.out.println("Deleted Kathleen Turner:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
}
}
Candidate
public class Candidate
{
// instance variables
int numVotes;
String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}
When you "delete" array elements, after the shift you assign null to the most right element of the array.
In your getTotal() you traverse the entire array and retrieve the value of numVotes for each element. When you reach the null element you are getting the exception since null does not have any fields..

Convert Hex value to ASCII character from array and how to eliminate null value?

I'm in the middle trying to convert the hex value that I retrieved from my method, compareHexaRGB to ASCII character which I want to know what output is going to produce. I don't know if I'm doing it wrong or I missed to code somewhere.
Code for extractMessage() method to convert hex value to ASCII:
public class extractMessage
{
private static String[][] char1;
private static String[][] char2;
private static String[][] in;
private static String[][] combine;
public static void extractMessage(String[][] inn, String[][] comb)
{
in = inn;
combine = comb;
}
public static void printString2DArray(String[][] in)
{
for (int i = 0; i < in.length; i++)
{
for(int j = 0; j < in[i].length; j++)
{
System.out.println(in[i][j] + " ");
}
System.out.println();
}
}
public static void charExtract()
{
compareHexaRGB hexRGB = new compareHexaRGB();
char1 = hexRGB.getCheck_hex2();
char2 = hexRGB.getCheck_hex4();
combine = new String[char1.length][char1[0].length];
for(int i = 0; i < char1.length; i++)
{
for(int j = 0; j < char1[i].length; j++)
{
//concatenate string
combine[i][j] = char1[i][j] + char2[i][j];
}
}
System.out.println("Char 1 + Char 2: ");
printString2DArray(combine);
}
public static String convertHexToString()
{
extractMessage em = new extractMessage();
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
String out = em.charExtract(); //error stated incompatible types: void cannot be converted to String
int decimal;
for(int i = 0; i < out.length(); i += 2)
{
String output = out.substring(i, (i + 2));
decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Output: " + temp.toString());
return sb.toString();
}
}
Second, I still cannot eliminate the NULL value from the retrieved value. Someone said I need to add a place to hold the characters which in this case the NULL value. I've done that but when I try to run the code then, here we go again, the nullpointerexception occur. I'm still new to java and lack of experience handling with java arrays and advanced java but I'm eager to learn. Java is very interesting language and I hope one day I could master on this language.
Code for compareHexaRGB() :
public class compareHexaRGB
{
private static int w;
private static int h;
private static BufferedImage img;
private static BufferedImage img2;
private static String[][] check_hex2;
private static String[][] check_hex4;
private static String[][] not_stega2;
private static String[][] not_stega4;
public static void compareHexaRGB(BufferedImage image, BufferedImage image2, int width, int height) throws IOException
{
w = width;
h = height;
img = image;
img2 = image2;
}
public void check() throws IOException
{
getPixelRGB1 pixel = new getPixelRGB1();
getPixelData1 newPD = new getPixelData1();
int[] rgb;
int count = 0;
int[][] pixelData = new int[w * h][3];
check_hex2 = new String[w][h];
check_hex4 = new String[w][h];
for(int i = 0; i < w; i++)
{
for(int j = 0; j < h; j++)
{
rgb = newPD.getPixelData(img, i, j);
for(int k = 0; k < rgb.length; k++)
{
pixelData[count][k] = rgb[k];
}
if(pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]))
{
System.out.println("\nPixel values at position 2 are the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j]);
not_stega2[i][j] = pixel.display_img2Hex2()[i][j]; // i've done the same as check_hex2 and check_hex4 method but why the error still occur?
}
if(pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]))
{
System.out.println("\nPixel values at position 4 are the same." + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
not_stega4[i][j] = pixel.display_img2Hex4()[i][j];
}
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]))
{
System.out.println("\nPixel values at position 2 are not the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j]);
check_hex2[i][j] = pixel.display_img2Hex2()[i][j];
System.out.println("\nOutput Hex 2: " + check_hex2[i][j]);
}
if(!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]))
{
System.out.println("\nPixel values at position 4 are not the same." + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
check_hex4[i][j] = pixel.display_img2Hex4()[i][j];
System.out.println("\nOutput Hex 4: " + check_hex4[i][j]);
}
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]) || (!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j])))
{
System.out.println("\nOne of the pixel values at position 2 and 4 are not the same." + "\n" + pixel.display_imgHex2()[i][j] + " " + pixel.display_img2Hex2()[i][j] + "\n" + pixel.display_imgHex4()[i][j] + " " + pixel.display_img2Hex4()[i][j]);
if(!pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j]) || (pixel.display_imgHex2()[i][j].equals(pixel.display_img2Hex2()[i][j])))
{
check_hex2[i][j] = pixel.display_img2Hex2()[i][j];
System.out.println("\nOutput Hex 2: " + check_hex2[i][j]);
}
if(!pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j]) || (pixel.display_imgHex4()[i][j].equals(pixel.display_img2Hex4()[i][j])))
{
check_hex4[i][j] = pixel.display_img2Hex4()[i][j];
System.out.println("\nOutput Hex 4: " + check_hex4[i][j]);
}
}
count++;
System.out.println("\nOutput Count: " + count);
}
}
}
public String[][] getCheck_hex2()
{
return check_hex2;
}
public String[][] getCheck_hex4()
{
return check_hex4;
}
public String[][] getCheck_notStega2()
{
return not_stega2;
}
public String[][] getCheck_notStega4()
{
return not_stega4;
}
}
Hoping to eliminate these problems fast. Appreciate any help!
As i see there are 2 flaws in your code::
1. If charExtract() method is static then you need to access it in a static way as::
String out = extractMessage.charExtract();
2. Secondly as you are storing the value from charExtract() to a String variable "out"
so you need to return a string from the charExtract() method ,Declare it as
public static String charExtract()
{ ...
}
and return some value from charExtract like:
return combine[o][1];
public static void charExtract()
{ ...
}
and
String out = em.charExtract(); //error stated incompatible types
obviously don't match. Besides, why are you trying to call the static method charExtract() upon the instance em?
What do you store in those String[][] arrays?
char1 = hexRGB.getCheck_hex2();
char2 = hexRGB.getCheck_hex4();
Without knowing what they are supposed to contain, we cannot help you convert their content to anything.
At the moment I assume that you don't really want to deal with "hex" numbers; calculations are much easier performed on ints than on any String representation of numbers.

what is wrong with this code when dealing with large values of "long"?

I wrote an utility class to encode numbers in a custom numeral system with base N. As any self-respecting Java programmer I then wrote a unit test to check that the code works as expected (for any number I could throw at it).
It turned out, that for small numbers, it worked. However, for sufficiently large numbers, the tests failed.
The code:
public class EncodeUtil {
private String symbols;
private boolean isCaseSensitive;
private boolean useDefaultSymbols;
private int[] symbolLookup = new int[255];
public EncodeUtil() {
this(true);
}
public EncodeUtil(boolean isCaseSensitive) {
this.useDefaultSymbols = true;
setCaseSensitive(isCaseSensitive);
}
public EncodeUtil(boolean isCaseSensitive, String symbols) {
this.useDefaultSymbols = false;
setCaseSensitive(isCaseSensitive);
setSymbols(symbols);
}
public void setSymbols(String symbols) {
this.symbols = symbols;
fillLookupArray();
}
public void setCaseSensitive(boolean isCaseSensitive) {
this.isCaseSensitive = isCaseSensitive;
if (useDefaultSymbols) {
setSymbols(makeAlphaNumericString(isCaseSensitive));
}
}
private void fillLookupArray() {
//reset lookup array
for (int i = 0; i < symbolLookup.length; i++) {
symbolLookup[i] = -1;
}
for (int i = 0; i < symbols.length(); i++) {
char c = symbols.charAt(i);
if (symbolLookup[(int) c] == -1) {
symbolLookup[(int) c] = i;
} else {
throw new IllegalArgumentException("duplicate symbol:" + c);
}
}
}
private static String makeAlphaNumericString(boolean caseSensitive) {
StringBuilder sb = new StringBuilder(255);
int caseDiff = 'a' - 'A';
for (int i = 'A'; i <= 'Z'; i++) {
sb.append((char) i);
if (caseSensitive) sb.append((char) (i + caseDiff));
}
for (int i = '0'; i <= '9'; i++) {
sb.append((char) i);
}
return sb.toString();
}
public String encodeNumber(long decNum) {
return encodeNumber(decNum, 0);
}
public String encodeNumber(long decNum, int minLen) {
StringBuilder result = new StringBuilder(20);
long num = decNum;
long mod = 0;
int base = symbols.length();
do {
mod = num % base;
result.append(symbols.charAt((int) mod));
num = Math.round(Math.floor((num-mod) / base));
} while (num > 0);
if (result.length() < minLen) {
for (int i = result.length(); i < minLen; i++) {
result.append(symbols.charAt(0));
}
}
return result.toString();
}
public long decodeNumber(String encNum) {
if (encNum == null) return 0;
if (!isCaseSensitive) encNum = encNum.toUpperCase();
long result = 0;
int base = symbols.length();
long multiplier = 1;
for (int i = 0; i < encNum.length(); i++) {
char c = encNum.charAt(i);
int pos = symbolLookup[(int) c];
if (pos == -1) {
String debugValue = encNum.substring(0, i) + "[" + c + "]";
if (encNum.length()-1 > i) {
debugValue += encNum.substring(i + 1);
}
throw new IllegalArgumentException(
"invalid symbol '" + c + "' at position "
+ (i+1) + ": " + debugValue);
} else {
result += pos * multiplier;
multiplier = multiplier * base;
}
}
return result;
}
#Override
public String toString() {
return symbols;
}
}
The test:
public class EncodeUtilTest {
#Test
public void testRoundTrip() throws Exception {
//for some reason, numbers larger than this range will not be decoded correctly
//maybe some bug in JVM with arithmetic with long values?
//tried also BigDecimal, didn't make any difference
//anyway, it is highly improbable that we ever need such large numbers
long value = 288230376151711743L;
test(value, new EncodeUtil());
test(value, new EncodeUtil(false));
test(value, new EncodeUtil(true, "1234567890qwertyuiopasdfghjklzxcvbnm"));
}
#Test
public void testRoundTripMax() throws Exception {
//this will fail, see above
test(Long.MAX_VALUE, new EncodeUtil());
}
#Test
public void testRoundTripGettingCloserToMax() throws Exception {
//here we test different values, getting closer to Long.MAX_VALUE
//this will fail, see above
EncodeUtil util = new EncodeUtil();
for (long i = 1000; i > 0; i--) {
System.out.println(i);
test(Long.MAX_VALUE / i, util);
}
}
private void test(long number, EncodeUtil util) throws Exception {
String encoded = util.encodeNumber(number);
long result = util.decodeNumber(encoded);
long diff = number - result;
//System.out.println(number + " = " + encoded + " diff " + diff);
assertEquals("original=" + number + ", result=" + result + ", encoded=" + encoded, 0, diff);
}
}
Any ideas why things start failing when the values get large? I also tried BigInteger, but it did not seem to make a difference.
You're using floating point maths in your encodeNumber method, which makes your code rely on the precision of the double type.
Replacing
num = Math.round(Math.floor((num-mod) / base));
with
num = (num - mod) / base;
Makes the tests pass. Actually
num = num / base;
Should work just as well (thought experiment: what is 19 / 10 when / is integer division?).
You have a conversion to double in your code, which could be generating strange results for large values.
num = Math.round(Math.floor((num-mod) / base));
that would be my first port of call.

Categories

Resources