Using edwards revised code, i now have this:
int k, l, tempA, tempB;
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
// increment # and convert into string
buttonNumber++;
buttonName = Integer.toString(buttonNumber);
// assign new button to the array
cardButton[k * 4 + l] = new JButton(buttonName);
// assign button image icon
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
// assign value to the check variable
check[k * 4 + l] = Integer.toString(tempA+1);
// make button invisible for now
cardButton[k * 4 + l].setVisible(false);
// add the button to the board
board.add(cardButton[k * 4 + l]);
}
}
but my problem with this is that I need a replacement for the nested loop because the way it is set up now, it displays x value in 4 different suits before displaying the next value, when what i need is for it to display x value and x suit without repeating a value once, unless done randomly. The reason this is happening is because of the nested loop which iterates through k once, and then through l four times.
I believe your for-loop condition is incorrect.
j < 52 || k < 13 || l < 4 will return true until j >= 52. Looking at your code, this throws an out of bounds error because k and l will also increase to 52. If I were you, I'd place them in separate conditions.
It appears (according to your comment) that you want to iterate over a 2D array. In that case, I'd use 2 for-loops:
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
check[k * 4 + l] = Integer.toString(tempA+1);
}
}
Note that we're replacing your j variable with some math instead. Every time you go through your l loop, k is incremented by one. Thus, we can tell what card we're on by multiplying k by 4, since l goes through 4 times. If we add l, we can get the current card that you're looking at. This code should work right out of the box.
Edit: Your full code should be as followed.
int k, l, tempA = 0, tempB = 0;
// create temporary variables
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
// increment # and convert into string
buttonNumber = buttonNumber+1;
buttonName = Integer.toString(buttonNumber);
// assign new button to the array
cardButton[k * 4 + l] = new JButton(buttonName);
// assign button image icon
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
// assign value to the check variable
check[k * 4 + l] = Integer.toString(tempA+1);
// make button invisible for now
cardButton[k * 4 + l].setVisible(false);
// add the button to the board
board.add(cardButton[k * 4 + l]);
}
}
Also, instead of doing buttonNumber = buttonNumber + 1, you can use buttonNumber++
If you're trying to get every permutation of rndm and suit, you'll need a nested loop:
for (int i = 0; i < 13; i++) {
for (int j = 0; j < 4; j++) {
tempA = rndm.get(i);
tempB = suit.get(j);
//...
}
}
You are misunderstanding how logical operators work. Double vertical bar is "or" operator. It takes two expressions that can be casted to boolean values and returns true if at least one of them is true.
boolean test = (1 == 2 || 5 < 3);
// test == true
Your for loop is iterating outside of the array bounds. Let's simplify your code a little bit. Let's create two arrays with fixed size, 1 and 2 elements, and then iterate over them in a loop similar to yours.
Integer[] arrayA = new Integer[1];
Integer[] arrayB = new Integer[2];
for (int i = 0, j = 0; i < 1 || j < 2; i++, j++) {
arrayA[i] = i; // Will throw ArrayIndexOutOfBounds
arrayB[j] = j;
}
Now, let's see how the counters will change during loop execution:
i == 0 and j == 0, i < 1 == true and j < 2 == true, we increment both
i == 1 and j == 1, i < 1 == false but still j < 2 == true, one of the conditions is true (and we need only one to be true in order for || operator to return true) so the loop code is executed even though i index is out of bounds!
Your code throws an exception for the same reason. Even though l < 4 == false, whole condition evaluates to true, therefore loop code will be executed.
What you want is to change all of the || operators to &&:
for (j = 0, k = 0, l = 0; j < 52 && k < 13 && l < 4; j++, k++, l++)
You can read more about boolean algebra and difference between and and or operators here - http://www.tutorialspoint.com/computer_logical_organization/boolean_algebra.htm
On a side note, don't do loops like that. So many variables in one statement are very confusing, as you might have noticed. Consider using enchanced for loops if you are always accessing objects with the exact same index as your counter variable.
Related
I'm trying to put an array of String into an array of 2d char diagonally. I'm having an issue producing the range of my random number so that it would be in the indexes of my 2D array. My code works but sometimes it would break, giving a "java.lang.ArrayIndexOutOfBoundsException: 60".
useWords is an array of String that the user enter and puzzleBoard is a 2d array of 60 rows and 30 columns.
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(60);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r+j][c+j] = userWords[i].charAt(j); // -j-j = dia right backward || +j+j= dia right forward || -j+j dia forward || +j-j dia backward
}
}
This is the output if the code doesn't break.
Given your code:
1 for (int i = 0; i < userWords.length; i++) {
2 int r = rand.nextInt(60);
3 int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
4 for (int j = 0; j < userWords[i].length(); j++) {
5 puzzleBoard[r+j][c+j] = userWords[i].charAt(j); // -j-j = dia right backward || +j+j= dia right forward || -j+j dia forward || +j-j dia backward
6 }
7 }
8 }
The value for r + j in line 5 can easily become larger than 59, as r by itself can already be 59. That way, your array will become out of bounds, hence the java.lang.ArrayIndexOutOfBoundsException: 60.
You could use (r + j) % 60 as a solution to continue at the left side of the board.
I'm trying my hands on basic programming and I came across this question. I have a function with a return type as string, that takes an integer input and has to print the series mentioned. Here's what I did.
String s=new String("h");
int[] a=new int[n];
int k=1;
for(int i=0;i<n;i+=2)
{
a[i]=b;//line6
a[i+1]=n-(b-1);//line7
b++;
}
s=Arrays.toString(a);
return s;
When I enter an "even" no. like 4. I get the proper result [1,4,2,3].
But when I enter "odd" no. like 5. I get an ArrayOutOfBoundException
I Know where Im going wrong at line6 and line7 but I'm not getting an idea how to modify it accordingly.
I also wish to return the string as 1 n 2 n-1 3 n-2 ... instead of [1,n,2,n-1,3,n-2,..]
That's because you have a loop running from i = 0 to i < n, and you are trying to access a[i + 1]. This runs fine on even numbers because you're incrementing 2 each time, and the last iteration checks for a[n - 2] and a[n - 1].
The ArrayIndexOutOfBoundException occurs on odd numbers, however, because the last iteration attempts to access a[n - 1] and a[n].
One way to modify the loop would be to increment only by 1, and set the value of a[i] by checking the parity of i inside the loop:
for(int i = 0; i < n; i++, b++) {
a[i] = (i % 2 == 0)? b: (n - (b - 1));
}
consider the next approach:
for(int i=0;i<n/2;i++)
{
a[2*i] = i+1;
a[2*i+1] = n-i;
}
if (n&1==1) //how to check for oddity in Java?
a[n-1] = (n+1)/2
The inside of your loop should look like
a[i] = b;
if (i + 1 < n) { // check the bounds before writing at i+1
a[i + 1] = n - (b - 1);
}
b++;
The reason for that is that when having odd numbers (e.g. 5) i gets to become 4 in the last iteration of the loop, 4 is smaller than 5, therefore the code enters the loop, then you access a at index 4, which is okay, but then you try to access it at 4+1, which is 5, but the array does not have an index 5 because.
Split the problem up into two smaller problems:
Generating all values for even indices
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
Generating all values for odd incides
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
Thanks to integer-division i / 2 of an odd number can substitute (i - 1) / 2.
Full code
int[] a = new int[n];
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
return Arrays.toString(a);
I am very new to Java and am currently learning about arrays. Our homework this week is to
"Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable"
My question is this. Is the value in the element at an index position considered the index variable. For example if alpha[2] = 3 would 3 be the index variable, and in reading the assignment I would then square 3.
The other thought that I would have is that I have to square the index number [0],[1],[2]...
Thank you for any input, and I apologize if this is in the wrong area.
Thank you for the input so far. What I am trying to get to is what exactly is an "Index Variable"
Here is what I did
// Import various packages to be used in the program
import java.util.*;
import java.lang.*;
public class module5
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
// Declare an array called alpha with 50 pre-defined elements
double []alpha = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
// Process the first 25 elements
for (int i = 0; i < 25; i++) {
// Square the first 25 elements
alpha[i] = Math.pow(alpha[i], 2);
}
// Process the second set of 25
for (int i = 25; i >= 25 && i < 50; i++) {
// Multiply by 3
alpha[i] = alpha[i] * 3;
}
for (int i = 0; i < alpha.length; ++i) {
System.out.print(alpha[i]);
if (i % 10 == 9) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
}
No. In alpha[2] = 3 2 is the index variable, and 3 is the value being indexed. The other thought that I would have is that I have to square the index number [0],[1],[2] Correct.
alpha[0] = 0 * 0;
alpha[1] = 1 * 1;
alpha[2] = 2 * 2;
// ...
alpha[25] = 3 * 25;
// ...
alpha[49] = 3 * 49;
You are expected (I think) to use a loop with a conditional (but you might also use two separate loops with different initial and terminal conditions) to do these assignments.
You are dealing with int(s), so use an int[]. Something like,
int[] alpha = new int[50];
Then you might use a single for loop like,
for (int index = 0; index < alpha.length; index++) {
if (index < 25) {
alpha[index] = index * index;
} else {
alpha[index] = index * 3;
}
}
or two loops like
for (int index = 0; index < 25; index++) {
alpha[index] = index * index;
}
for (int index = 25; index < alpha.length; index++) {
alpha[index] = 3 * index;
}
or using a ternary (conditional operator ? :) and a loop like
for (int index = 0; index < alpha.length; index++) {
alpha[index] = index * ((index < 25) ? index : 3);
}
The index of an array element is the number in the brackets, [].
In the example, alpha[2] = 3, 2 is the index and 3 is the variable stored at index 2.
Also remember that for arrays, index 2 means that it is the third position in the array because the first index is position 0.
For this exercise, you would declare an index variable, i, and iterate through the array such that alpha[0] = 0, alpha[1] = 1, alpha[2] = 4, ... alpha[i] = i*i
I'm trying to increment the following sequence in a for loop (Java):
1, 4, 9, 16, 25 etc the difference increasing by two each time. I tried using 'i+=3 + i' but I know that's wrong since it doesn't take into account that the variable i changes along the sequence.
Any help? Thanks
You could have an increment of i+=k and change k inside the loop in order to change the increment.
int k=1;
for (int i=1;i<1000;i+=k) {
k+=2;
}
If your i is changing, the simple logic is, use another variable that is declared outside the scope of the loop. This will make sure that it is not recreated everytime the loop runs.
int num = 1;
for(int i=1; i<maxValue; num+=2,i+=num){
//Use the value of `i` here, it will be as you wanted.
}
The sequence is to start with j=1 and k=4 and then derive next values of the series n times. The formula as follow:
Initial loop (i=0):
j = 1, k = 4;
Loop (i > 0 less than n):
Repeat below n times:
temp = k;
k = k + (k - j + 2);
j = temp;
print value of j being the series;
I assume that you take n as input from user and then generate the series nth times. Let's look at the following code example
int n = 10;
for(int i = 0, temp = 0, j = 1, k = 4; i < n; i++, temp = k, k += (k-j+2), j = temp) {
System.out.println(j);
}
Assuming that user inputs n = 10, the loop initializes i = 0 and continues until i < n is satisfied. It initializes j = 1 and k = 4 and then execute the body of the loop (printing j) followed by backing up the value of k, calculating new value for k and replacing the old value of j. The output for n = 10 is as follow:
1
4
9
16
25
36
49
64
81
100
Read Series number from the user and generate series based on given number.
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans;
for(int i = 1; i <= n; i++){
ans = i * i;
System.out.println(ans);
}
I'm trying to work out the difference in adjacent pairs of array elements, and then add the differences together, this is the method I'm using to do this.
I'm trying to split the original array into two smaller arrays and then subtract elements of the smaller arrays which will indirectly workout the difference of my initial array. the diffrences get stored on a last array which adds my differences together....
public static int changeinx(int array1[],int sum) {
int n = array1.length;
int y[];
int u[];
int c[];
c = new int [n/2];
y = new int [n/2]; // no. of arrays equal to 1/2 of array1, since two elements subtracted.
u = new int [n/2];
for(int i = 0 ; i < n ; i += 2 ) {
y[i] = array1[i];
}
for(int i = 1 ; i < n ; i += 2) {
u[i] = array1[i];
}
for(int i = 0 ; i < n/2 ; i++ ) {
c[i] = Math.abs( u[i] - y[i] ) ;
}
for(int r = 0 ; r < c.length ; r++ ) {
sum = sum + c[r]; //adding all the differences up, since abs has been taken
}
return sum ;
}
Why is this not working? :(
I find a major flaw in this loop:
for(int i = 0 ; i < n ; i++) {
int x = array1[i] - array1[i+1] ;
Let me give an example to illustrate this further, say we have an array
array1 = 25 15 55 12
the above loop at first iteration would do 25-15
in the 2nd iteration do 15-55
and 3rd iteration do 55-12
So now running this loop on an array of 4 elements would yield an array with 3 elements not at all conforming to your n/2 formula.
From my understanding of your problem I think your intention is to do 25-15 in the first loop
55-12 in the 2nd loop and end it, as to how you would go about doing it I leave it to you to figure out
This loop never ends:
for(int p = 0 ; p < n ; i++ ) {
y[p] = Math.abs(x); //trying to the difference as x, and asign to array y[]
}
Since p and n never change during the loop, if p < n is not true when the loop starts, it will never be true, and the loop will never end.
I'm trying to work out the difference in adjacent pairs of array elements, and then add the differences together, this is the method I'm using to do this.
If I understood the problem description correctly, this can be implemented much simpler:
public static int changeinx(int[] arr) {
int sumOfDiffs = 0;
for (int i = 0; i < arr.length - 1; i++) {
sumOfDiffs += Math.abs(arr[i] - arr[i + 1]);
}
return sumOfDiffs;
}