gpt4 book ai didi

java - 用整数序列填充数组并打印的方法

转载 作者:行者123 更新时间:2023-12-01 09:25:01 26 4
gpt4 key购买 nike

我有一个关于如何编写一个用整数填充数组的方法的问题。我做了这个方法,但我对如何打印它感到困惑。我应该在每个方法中从 for 循环开始吗?我该如何将它们打印在一行上,每个数字之间有一个空格,如下所示:[1 2 3 4 5 6 7 ... 50]?

public class Numbers {
public int[] numbers;

public Numbers() {
numbers = new int[50];
}

public void numSequence() { // filling the array with sequence of integers.
for(int i = 0; i < 50; i++) {
numbers[i] = i;
}
}

public void printArray() { // printing the array
// do I need for loop here
for(int i = 0; i < 50; i++) {
System.out.print(i+1);
}
}

public static void main(String[] args){
Numbers d = new Numbers();

d.numSequence();
d.printArray();
}
}

最佳答案

您的 printArray 方法未打印数组。它正在打印 for 循环的索引。因此,首先,打印实际的数组值。

此外,通过该打印,您可以在每个字母后添加自己的空格。

例如

public void printArray() { // printing the array
System.out.print("["); // not in loop
for(int i = 0; i < numbers.length; i++) { // loop through numbers array
System.out.print(numbers[i]); // print the element in the array
if (i != numbers.length - 1) { // not the last element, so print a space
System.out.print(" ");
}
}
System.out.print("]"); // not in loop
}

但是接下来你会遇到一个问题。因为当您创建 numbers 数组时,您是从 0 开始的,而不是从 1 开始的。现在,您可以通过将 1 添加到 numbers 数组来解决此问题,就像您在问题中所做的那样。但这是不好的做法,因为您可以一开始就正确创建数组。因此,将您的 numSequence 方法更改为:

public void numSequence() { // filling the array with sequence of integers.
for(int i = 1; i <= 50; i++) { // starts at 1, and <= 50 so it adds 50 too
numbers[i] = i;
}
}

关于java - 用整数序列填充数组并打印的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907623/

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