简体   繁体   中英

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  "); 
            
    }

try to change this:

    for(int x = 0; x <= values.length; x++) {
        digits[values[x] -1]++;
    }

to this:

    for (int x = 0; x < values.length ; x++) {
        digits[values[x]]++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM