[英]How do I rewrite my code so that the value of 0 does not give me a out of bounds error in java?
package problems;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Single {
public static void main(String[] args) {
//create the array of random integers
int[] values = new int[10];
//Assign random values to each space in the array
for(int x = 0; x <values.length; x++) {
int y;
y = (int) (Math.random() * 10);
values[x] = y;
}
System.out.println(Arrays.toString(values));
//The digits array is an array with 10 random integers
//Create an array that holds the 10 digits (0-9)
int[] digits = new int[10];
for(int x = 0; x <= values.length; x++) {
digits[values[x] -1]++;
}
//display each count of the numbers
for(int x = 0; x <values.length; x++)
if ((x + 1) % 5 == 0)
System.out.println(digits[x] + " " + (int)(x + 1));
else
System.out.print(digits[x] + " " + (int)(x + 1) + "'s ");
}
尝试改变这一点:
for(int x = 0; x <= values.length; x++) {
digits[values[x] -1]++;
}
对此:
for (int x = 0; x < values.length ; x++) {
digits[values[x]]++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.