This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 3 years ago.
I am currently working on a program that will roll 5 dice and store a random number for each dice in an array.
My problem is my method is only changing the first element and leaving the rest of the elements as 0's. (Only rolling the first dice so to say)
I initialized an array with 5 values, then run this method which takes an array as a parameter, checks if an element is 0, if it is it assigns a random value between 1 and 6.
I've tried doing an enhanced for loop that looks at each element in the array, and theoretically if it is zero, it assigns a random integer between 1 to 6 to it.
public static void rollDice(int[] dice) {
for (int element: dice) {
int roll = (int)(Math.random()*6) + 1;
if (element == 0) {
dice[element] = roll;
}
}
My results are currently: [Random Number, 0, 0, 0, 0]
My expected results are: [5 random integers]
This form of the Java for loop loops over the values, not the indexes, of the array. All of the values are 0 and you're using them as the index. You are setting the first element 5 times because of this.
Use a traditional for loop.
for (int index = 0; index < dice.length; index++) {
// Your roll here
dice[index] = roll;
}
Here
if (element == 0) {
dice[element] = roll;
}
your code says that if it is the first element, then store the result of the randomization. Since other elements are not the first element, in the case of other elements the condition will be false and consequently the roll will not be stored. Remove this if:
//if (element == 0) {
dice[element] = roll;
//}
public static void rollDice(int[] dice) {
for (int i=0;i<dice.length;i++) {
int roll = (int)(Math.random()*6) + 1;
if (dice[i]== 0) {
dice[i] = roll;
}
}
you were changing index 0 5 times because you put the value of array position 0 as the index to change
In dice[element] :
element is NOT the index of the loop, it's the value of the element in the array.
In your case, element is always 0 because java puts 0s in newly created arrays.
You should use an ordinary for loop in this case:
for (int i = 0; i < dice.length; i++) {
int roll = (int) (Math.random() * 6) + 1;
if (dice[i] == 0) {
dice[i] = roll;
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
This is an example of using access modifiers to avoid generating exceptions:
class FailSoftArray {
private int a[];
private int errval;
public int length;
public FailSoftArray(int size, int errv) {
a = new int[size];
errval = errv;
length = size;
}
public int get(int index) {
if(indexOK(index)) return a[index];
return errval;
}
public boolean put(int index, int val) {
if(indexOK(index)) {
a[index] = val;
return true;
}
return false;
}
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
public class TestMethod {
public static void main(String[] args) {
FailSoftArray333 fs = new FailSoftArray(5, -1);
int x;
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
for(int i =0; i < (fs.length * 2); i++) {
x = fs.get(i);
if(x != -1) System.out.print(x + " ");
else
System.out.println("Index " + i + " outside the range of the array");
}
}
}
I don't understand why in this case I have to use the operator (!) for the code to work correctly:
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
When I print it with (!) the results are what you would expect:
Error access message..
Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
Without (!):
Error access message..
Index 0 outside the range of the array
Index 1 outside the range of the array
Index 2 outside the range of the array
Index 3 outside the range of the array
Index 4 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
Can someone explain to me how exactly the operator (!) works in this case? Why is it needed and how does it affect the method?
The put function of FailSoftArray returns a boolean value true/false whether it was able to successfully put the new value val at index index within array a
The ! signifies a logical NOT
By using if(!fs.put(i, i*10)), you are effectively telling the compiler
if(put was NOT able to place i*10 at index i)
System.out.println("Index " + i + " outside the range of the array");
Leaving the ! out would be like saying
if(put succeeded)
//Print error
which is obviously not intended
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a simple for loop which prints the content of an integer array. It keeps throwing java.lang.ArrayIndexOutOfBoundsException exception. I have been scratching my head for couple of hours not knowing what is that I am doing wrong
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 10; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
The ArrayIndexOutOfBoundsException is thrown because you try to access the 11th element in a 10 element array.
Arrays use zero-based indexing, which means that when you do nums[0] you are trying to access the first element of the Array. So:
int[] nums = {100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);
will print
100
As a result of this, when you do nums[10], you are trying to access the 11th element, which doesn't exist. To fix this, you can start on index 9 instead of 10, like:
for(int i = 9; i >= 0; i--){ // "i" starts with a value of 9, so it works
System.out.print(nums[i] + " ");
}
Arrays in most programming language are indexed from 0 by default, so that means the first element which is 100 has an index of 0, so u access it as nums[0]. So from this u can realize that the last element in ur array has an index of 9 which is nums[9] ==10.
ur getting this error because ur trying to access the element at the 10th index even though ur array has elements only upto 9th index i.e nums[0] = 100, nums[1] = 90 ..... nums [9] = 10.
just change the i to 9 like this and it will work like a charm
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 9; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
This question already has an answer here:
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 4 years ago.
I don't get how can it be out of bounds if I bound i by the array size. I get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 116, Size: 116
eratosthenes(ArrayList <Integer> array) checks for primal every element and deletes it if true, then the process is repeated for the next remained element.
package arrays;
import java.util.*;
public class Examples {
public static void main(String[] args) {
ArrayList <Integer> array = getFilledArrayList(2, 1000);
eratosthenes(array);
System.out.println(array.toString());
}
private static void eratosthenes(ArrayList <Integer> array) {
int index = 0;
int primal = array.get(index);
while (index < array.size() - 1) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % primal == 0) array.remove(i);
}
index++;
primal = array.get(index);
}
}
private static ArrayList <Integer> getFilledArrayList(int start, int stop) {
ArrayList <Integer> array = new ArrayList();
for (int i = start; i < stop + 1; i++) {
array.add(i);
}
return array;
}
}
Array bounds are 0-indexed, meaning that the first element in an array is found at index 0. Therefore, the last index that is within the bounds of an array is the array size minus 1. Thus, the bounds of an array in Java span from [0, length - 1], or stated another way, [0, length).
The culprit is the following snippet:
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % primal == 0) array.remove(i);
}
index++;
primal = array.get(index);
If array.remove(i) is called within the loop, the number of values in array is reduced. Paired with the increment of index in the index++ line, this may push index beyond the bounds of array causing an IndexOutOfBoundsException.
For example, if array has a length of 1000 and index has a value of 998, calling array.remove(i) causes the length of array to be reduced to 999. The increment of index causes index to have a value of 999, which is equal to the length of array, resulting in an IndexOutOfBoundsException.
array.size() -1, since the array index starts at zero
I am trying to iterate through a randomly generated 2d array of 0s, and 1s. In this method which I am stuck on I am trying to see if the subdiagonal has all the same numbers, all 1s, all 0s, or different numbers.
sub diagonal meaning:
110
101
011
The 0s are the subdiagonal.
this is the code I have as of now. I am trying to iterate starting at the last row and counting up to the first row diagonally.
int firstValue= matrix[matrix.length-1][0];
int result = -1;
for(int row = matrix.length-1; row > 0; row--)
{
int column = row;
if(firstValue == matrix[row][column])
{
result = firstValue;
continue;
}
else
{
result = -1;
break;
}
}
if(result== 1)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else if (result == 0)
{
System.out.println("All " + firstValue + "s on the subdiagonal");
}
else
{
System.out.println("Numbers on subdiagonal are different");
}
}
I'm almost certain my issue is with the firstValue and/or the for loop counting up the diagonal.
Any help would be appreciated, thanks much
Your issue seems to be at the following line,
for(int row = matrix.length-1; row > 0; row++) {
...
}
you are doing a
row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length
Then you will be accessing a index that does not exist causing a ArrayIndexOutOfBoundsException
Edit
what you'd want to do is,
for(int row = matrix.length-1; row >= 0; row--) {
....
}
This way you'd be able to iterate though your array from largest index to the smallest (0).
Edit 2
Let's say Staring array called arr has 4 elements. It'll be structured as below,
arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";
Array indexes always starts from 0, so the highest index in the above array is 3.
So if you want to iterate from smallest index to the largest, you'd do
for(int i = 0; i < arr.length; i++) {
//i's initial value is 0 and itll increment each time the loop runs
//loop will terminate when i is no longer < 4
System.out.println(arr[i]);
}
and to iterate through the array in reverse order you'd do,
for(int i = (arr.length - 1); i <= 0; i--) {
//i's initial value is (4 - 1) and it'll decrement each time the loop runs
//loop will terminate when i smaller or equal to 0
System.out.println(arr[i]);
}
So we want to check if all of the values in the subdiagonal are the same value, and if they are then we want to print the value that is the same. First we set aside a comparison to check the other indices
int checkValue = arr[0][arr[0].length-1];
This is the last value in the first row. Then we set a flag to catch whenever our index that we are checking matches our first value. We'll set it to false because we'll assume that the values don't match.
boolean flag = false;
Now that we have that, we need to iterate through each row in our array. We will start with the second row (arr[1]) and then we need to check the value one down and one over compared to the last value we checked (arr[1][arr.length - 1 - i]). If our first value (we assigned it's value to checkValue) and the value we are checking are the same, change the flag to true.
for (int i = 1; i < arr.length; i++)
if (arr[i][arr.length - 1 - i] != checkValue)
flag = true;
That'll run through all of the rows in the array. Now we have to check the state of our flag and print out the appropriate response. If the flag is true, print out that the values on the row are the same. Else we will say that the subdiagonal does not match all the way through.
if (!flag)//remember our flag is set to false, double negative equals true.
System.out.println("All of the values on the subdiagonal are the same");
else
System.out.println("All of the values on the subdiagonal are not the same");
I'm fairly new to java so I would like to keep it simple, and I figure I would have to take the first value of the array then compare it to each following value and if the value is larger smaller than the first, replace the value with it, but I don't know how to get index from that.
For an unstructured, unsorted array the best you can do, assuming you are only going to find the minimum value once, is a simple iteration over all elements (O(n) complexity), like so:
public int findMinIdx(int[] numbers) {
if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
// As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
int minVal = numbers[0] // Keeps a running count of the smallest value so far
int minIdx = 0; // Will store the index of minVal
for(int idx=1; idx<numbers.length; idx++) {
if(numbers[idx] < minVal) {
minVal = numbers[idx];
minIdx = idx;
}
}
return minIdx;
}
Also, in the case of a tie for minimum value, this method will return the index of the first case of that value it found. If you want it to be the last case, simply change numbers[idx] < minVal to numbers[idx] <= minVal.
Here is with Java 8
public static int findMinIdx(int[] numbers) {
OptionalInt minimun = IntStream.of(numbers).min();
return IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
}
Never cared about run time optimization, was just looking for a solution!, this worked and this would help you too, finding the index of the lowest values in an array.
// array[] -> Received the array in question as an parameter
// index -> stores the index of the lowest value
// in for loop, i is important to complete all the comparison in the function
// When it finds a lower value between the two, it does not change the index
// When it finds a lower value it changes it's index to that index
// If array has same value more than once, it will provide index to that values last occurrence
// Correct me if you find anything not working in this example...
//...
private static int index_of_minimum_value(int[] array) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
else if (array[index] > array[i]) index = i;
}
return index;
}