gpt4 book ai didi

java - 方阵程序

转载 作者:行者123 更新时间:2023-12-02 13:21:45 25 4
gpt4 key购买 nike

使用 java,我应该创建一个程序,将数字 0、1、2 和 9 的平方存储在 10 个元素的 ArrayList 中。

我已经创建了显示数字及其方 block 的部分代码,但程序直接向下显示所有数字,并且看起来没有组织。有人可以帮我像这样写出来吗:

数量:0 方格:0

数量:1 方格:1

数量:2 方格:4

代码

public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

for (int value : temp) {
System.out.println(value);
}

for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}

for (int value : temp) {
System.out.println(value);
}
}

最佳答案

你只需要一个这样的循环:

public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i] + "\t" + (int)Math.pow(temp[i], 2));
}
}

输出

0   0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
<小时/>

如果您想将结果存储在 ArrayList 中,您可以使用:

List<int[]> array = new ArrayList<>();//create a List which take an array of int

int arr[] = new int[2];//create a temporary array of 2 elements

for (int i = 0; i < temp.length; i++) {
System.out.println("Number: " + temp[i] + " \tSquare: " + (int) Math.pow(temp[i], 2));
arr[0] = temp[i];//add your number to your array pos 1
arr[1] = (int) Math.pow(temp[i], 2);//add the power to the 2ed position
array.add(arr);//add your array to your list

}

关于java - 方阵程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43546325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com