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

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]]++;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 Java 代码出现越界错误 - My Java code is giving me an out of bounds error 如何在Java代码中修复“坐标超出范围”错误? - How do I fix the “Coordinates out of bounds” error in my code in Java? 如何在Java中为复选框赋予一个值,例如“选择复选框时=加+ 20英镑”? - How do I give a value to my checkbox in java so for example, “when checkbox is selected = add + £20 total”? 我如何优化以下代码,使其可以接受任何数组大小并给我结果 - How do i optimize below code so that it can accept any array size and give me the result 是什么导致数组越界错误,如何清除代码? - What is causing the array out of bounds error and how can I clean up my code? 为什么这个 Java 代码会给出“字符串索引超出范围”错误? - Why does this Java code give an " String index out of range " error? 如何检查向量中向量的位置是否超出范围? - How do I check if a position in my vector of vectors is out of bounds? 我不断越界错误如何解决此问题? - I keep getting out of bounds error how do i fix this? 用我的多边形填充算法填充多边形会出现超出范围的错误 - Filling in polygon with my polygon fill algorithm give an out of bounds error 如何重写我的两个方法,以免出现 NullPointerException? - How to rewrite my two methods so I do not get a NullPointerException?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM