簡體   English   中英

如何重寫我的代碼,以使 0 的值不會在 java 中給我一個越界錯誤?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM