如何使用Java中的循环用整数填充数组

编程入门 行业动态 更新时间:2024-10-23 18:22:55
本文介绍了如何使用Java中的循环用整数填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是新手,我要完成一个练习,即编写一个简单的程序,该程序将在控制台中生成一个数组:

I am a newbie and I am to fulfill an exercise which is to write a simple program which would produce an array in console:

0,

0,1,

0,1,2,

我在Google上搜索类似的问题失败,这将使我找到解决办法.

I failed at google searching similar problems which would direct me at a solution.

非常感谢您的帮助.这就是我一直在尝试的基础,但是我完全陷入了困境:

I will greatly appreciate your help. This is what i have been trying to build upon, but I am completely stuck:

public static void main(String[] args) { // TODO Auto-generated method stub int[] table = new int[11]; for ( int i = 0; i <=10; i++){ table[i] = i; System.out.println(i); } }

推荐答案

您应使用 Arrays.toString ,如下所示:

import java.util.Arrays; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int[] table = new int[11]; for ( int i = 0; i <=10; i++){ table[i] = i; System.out.println(Arrays.toString(table)); } } }

但是,这将打印整个数组,因为它正在填充:

However, this will print the entire array, as it is being populated:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

如果您只想填充到目前为止的元素,那么它会涉及到更多一点:

If you just want the elements filled so far, it's a little more involved:

import java.util.Arrays; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int[] table = new int[11]; for ( int i = 0; i <=10; i++){ table[i] = i; for(int j = 0; j <= i; j++) { System.out.print((j == 0 ? "" : ", ") + table[j]); } System.out.println(); } } }

输出:

0 0, 1 0, 1, 2 0, 1, 2, 3 0, 1, 2, 3, 4 0, 1, 2, 3, 4, 5 0, 1, 2, 3, 4, 5, 6 0, 1, 2, 3, 4, 5, 6, 7 0, 1, 2, 3, 4, 5, 6, 7, 8 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

更多推荐

如何使用Java中的循环用整数填充数组

本文发布于:2023-08-05 21:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308137.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   数组   如何使用   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!