简单的Java数组程序 [英] Simple Java array program

查看:139
本文介绍了简单的Java数组程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将奇数存储在数组中,但是当我运行代码时,我得到的 9 是答案的五倍.它只存储值 9 .

I'm trying to store odd numbers in an array, but when I run the code I'm getting 9, five times as answer. It's only storing the value 9.

以下是代码:

public class Number2 {
    public static void main(String[] args) {
        int[] element = new int[5];

        for(int i=0; i<5; i++) {
            for(int j=1; j <= 10; j=j+2) {
                element[i] = j;
            }
        }

        for(int i=0; i < 5; i++) {
            System.out.println(element[i]);
        }
    }
}

您能告诉我我的程序出了什么问题吗?

Can you tell me what's wrong with my program?

推荐答案

您使用两个循环,而您只需要一个循环.当前,对于数组中的每个元素,都将其设置为1,然后设置为3,然后设置为5,然后设置为7,然后设置为9,每次都覆盖前一个值.因此,最后,您的数组就是 {9,9,9,9,9} .您可能想这样做:

You use two loops, where you would need only one. Currently for every element in your array, you set it to 1, then to 3, then to 5, then to 7, then to 9, overwriting the former value each time. Thus in the end, your array is just {9,9,9,9,9}. You probably wanted to do this:

for(int i = 0; i < element.length; i++) {
  element[i] = i*2 + 1;
}

这篇关于简单的Java数组程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆