【问题标题】:How do I rewrite my code so that the value of 0 does not give me a out of bounds error in java?如何重写我的代码,以使 0 的值不会在 java 中给我一个越界错误?
【发布时间】:2020-07-15 14:27:04
【问题描述】:
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  "); 
            
    }

【问题讨论】:

    标签: java indexoutofboundsexception


    【解决方案1】:

    尝试改变这一点:

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

    到这里:

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

    【讨论】:

    • 谢谢!一开始我是这样做的,但是打印的值不正确,所以我删除了最底部两个打印语句中的 (x+1)
    猜你喜欢
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 2021-04-03
    • 2018-05-30
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多