I'm writing a program to calculate the Hamming code, and I receive an array out of bounds exception. The issue seems to be with this method:
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
The integer m does not change it's value when using the Math.pow function on it. I've tried different things but I can't seem to make it work properly. The method is supposed to go through all powers of 2 as long as their value is lower than int[] inWord.length. After this it should assign parityBits[i] the value returned by the method processPower().
The exception received:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at hamming_code.HammingCoder.computeParityBits(HammingCoder.java:34)
at hamming_code.HammingCoder.computeHammingCode(HammingCoder.java:27)
at hamming_code.HammingCoder.main(HammingCoder.java:61)
A larger section of the code:
static int[] computeHammingCode(int[] inWord, int codeLength) {
int[] parityBits = new int[codeLength - inWord.length];
parityBits = computeParityBits(inWord, parityBits);
return parityBits;
}
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
}
static int processPower(int m, int[] inWord) {
int counter = 0;
for (int i = 0; i < inWord.length; i++){
for (int n = 0; n < m; n++) {
counter = counter + inWord[i];
}
for (int k = 0; k < m; k++) {
i++;
}
}
if (counter % 2 == 0) {
return 0;
} else
return 1;
}
Error message indicates that it fails for i = 5, but your loop is conditioned on the value of m, so something is wrong with your loop.
Printing the value of i and m for each iteration up to i = 5 will show you the error:
for (int i=0, m=2; i <= 5; i++) {
m = (int) Math.pow(m, i);
System.out.println(i + ": " + m);
}
OUTPUT (Ideone)
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
As you can see, m is always 1.
That is because first iteration calculates:
i=0,m=2: 2⁰ = 1
i=1,m=1: 1¹ = 1
i=2,m=1: 1² = 1
i=3,m=1: 1³ = 1
i=4,m=1: 1⁴ = 1
i=5,m=1: 1⁵ = 1
Debugging your code should have easily shown you this, faster than getting answer here.
I see nothing to prevent i from exceeding codeLength - inWord.length. That would account for the exception.
You get error because on fist iteration you have Math.pow(m, 0); and it equals to 1. Then m always will be 1, because power of 1 always 1. So i is incremented, but m not. But exit loop conditional m < inWord.length.
Related
I'm trying to print values by mapping one to another array. Below is my sample code.
int k;
int m=0;
int NUMBER_OF_TIME = 2; // this value will be constant won't change
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A, B"};
System.out.println("-----------------"+"\n");
for (k=0; k < array1.length; k++) {
inner: for (; m < timeReadings.length; m++) {
if(m==NUMBER_OF_TIME && k!=0) {
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
break inner;
}else
System.out.println(array1[k]+"\n");
System.out.println(timeReadings[m]+"\n");
}System.out.println("-----------------"+"\n");
}
Expected output is:
When user NUMBER_OF_TIME =2, the output should be like this.
--------------------
A
1 2 3 4 5 6
--------------------
B
7 8 9 10 11 12
--------------------
If i correctly understood what you want, this should work :
int NUMBER_OF_TIME = 2;
int n = 1;
boolean bool = true;
int[] timeReadings = {1,2,3,4,5,6,7,8,9,10,11,12};
String array1[] = {"A", "B"};
System.out.print("-----------------"+ System.lineSeparator());
System.out.print(array1[0] + System.lineSeparator());
for(int i : timeReadings) {
System.out.print(i + " ");
if(n > (timeReadings.length / NUMBER_OF_TIME) - 1 && bool) {
System.out.println(System.lineSeparator()+"-----------------");
System.out.print(array1[1] + System.lineSeparator());
bool = false;
}
n++;
}
System.out.println(System.lineSeparator()+"-----------------");
If this doesn't work for you, please provide more output examples, as others already asked.
Edit : Modified the code to output what you expect.
JAVA:
I want a for loop that doesnt stop when i is a certain number, but rather after x iterations. Is there any way to do that?
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7; i <= WHAT GOES HERE; i = i * 10 + i) {
sum = sum + i;
}
return sum;
}
You can declare multiple variables of the same type in a for-loop:
public static int seven_sum(int num) {
int sum = 0;
for (int i = 7, iterations = 0; iterations < (number of iterations); i = i * 10 + i, iterations++) {
sum = sum + i;
}
return sum;
}
Let's assume you have a certain value summing up in your loop and you want to stop the loop if the value exceeds a certain border. You can just add an if statement that checks the value:
public static void main(String args[]) {
// some value to hold a sum
int valueSum = 0;
for (int i = 0; i < 1000; i++) {
// in every iteration step, add the current value of i to valueSum
valueSum += i;
// print the current values of i and valueSum
System.out.println("Iteration no " + i + ", value sum = " + valueSum);
// stop looping if valueSum becomes 500 or greater
if (valueSum >= 500) {
break;
}
}
}
Please check the console output to get a better understanding of for loops and iteration in general.
The only case i can think of is: if x (number of iterations) is greater than i (your index which may depend on some input values like array length etc.) If that is the case you can combine an infinite loop with a break statement:
int iterations = 0;
for(int i = 0; true ; i++){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
or even without declaring an index:
int iterations = 0;
for( ; ; ){
System.out.println("iterations count = " + ++iterations);
if(iterations == 10) break;
}
or if you need two or more independent variables
int x = 10; //number of iterations wanted
for(int i = 7, j = 0; j<= x; i = i * 10 + i , j++){
// do something
}
I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}
Why is is giving me ArrayIndexOutOfBoundsException in second For loop?
public class Ass1Ques2 {
void rotate() {
int[] a = {3, 8, 9, 7, 6};
int r = 2;
int[] t1 = new int[(a.length - r) + 1];
int[] t2 = new int[r + 1];
for (int y = 0; y <= r; y++) {
t2[y] = a[y];
}
// This loop is giving error
for (int i = 0; i <= a.length - r; i++) {
t1[i] = a[i + r];
}
for (int f = 0; f <= t1.length; f++) {
System.out.println(t1[f] + " ");
}
for (int n = 0; n <= t2.length; n++) {
System.out.println(t2[n] + " ");
}
}
public static void main(String[] args) {
Ass1Ques2 r = new Ass1Ques2();
r.rotate();
}
}
I don't know how to fix this error,i think i have given the right length to t2.
I want to internally rotate the array clockwise according to r.
You access a[i+r], consider the last iteration of the loop. i = a.length-r so i+r = a.length-r + r = a.length which is out of bounds.
If you want to rotate the array, I recommend using the modulo (%) operator to compute the new position of an index. So in practice, add the rotation to all indices and modulo over the length of the array to get the new positions.
At the last iteration of the loop, you will be accessing a.length, which returns the entire length of the array starting at 1; which causes an IndexOutOfBounds exception since indices start at 0. In order to fix this, just do:
for (int i = 0; i < a.length - r; i++) {
t1[i] = a[i + r];
}
This will prevent the for loop from iterating to the very last spot of the array with an equal sign, which would've caused an IndexOutOfBounds exception.
I'm trying to run a method that calls my class method below. Everytime I call the method computeIterative(), I get an ArrayIndexOutOfBoundsException. I added some code to print out the loop, and I see that the exception occurs around the second time through the loop, but the loop continues until complete. What am I doing wrong that I can't solve this array exception?
static int computeIterative(int n) {
efficiency = 0;
int[] a = new int[n];
int firstInt = 0;
int secondInt = 1;
int results = 0;
if (n > 1) {
a[0] = 0;
a[1] = 1;
for (int i = 2; i <= n; ++i) {
efficiency++;
firstInt = a[i-1];
secondInt = a[i-2];
results = 2 * firstInt + secondInt;
System.out.println("Loop " + efficiency + " of " + n );
System.out.println(firstInt);
System.out.println(secondInt);
System.out.println("Results: " + results);
a[i] = results;
}
} else {
a[0] = 0;
a[1] = 1;
}
return a[n];
}
Thank you for the help.
the error lies in the line
a[i] = results;
since in your for loop, you have been using :
for(i=2;i<=n;i++)
You will find that the array index starts from 0 and goes up to n-1. So when you are using :
i <= n
you will encounter an array out of bounds exception because it does not have a 'n'th element.
Change your for loop condition from :
i <= n
to :
i < n
and your code should work.
You have initiated array with size "n", you are trying to access a[n] element, array index starts from 0 to n-1.So when you access a[n] you are getting Arrayindexboundexception.
change this line from
int[] a = new int[n]; to int[] a = new int[n+1]; (line 3)
Works!!
If n is 2, you access a[2] (a[i] = results;) but there are only element 0 and 1