gpt4 book ai didi

java - 从单独的 Java 主类打印 ArrayList

转载 作者:行者123 更新时间:2023-12-01 16:15:08 27 4
gpt4 key购买 nike

我的作业有很多问题,而我似乎唯一遇到麻烦的是 ArrayList 问题。我需要使用单独的 main 方法来输入和打印信息。

这是我的课

import java.util.ArrayList;

public class HailstoneSequence {

private int n;

public HailstoneSequence(int n) {
this.n = n;
}

public double getn() {
return n;
}

public static ArrayList<Integer> getHailstoneSequence(int n){
ArrayList<Integer> list = new ArrayList<Integer>();
//int i = 0;
while (n != 1);
for (int s : list) {
try {
if(n == 1) break;
if(n % 2 == 0) {
System.out.println(n + " is even, so I take half: " + (n / 2));
}
else
System.out.println(n + " is odd, so I make 3n+1: " + ((n * 3)+1));
// i++;
}
catch (Exception error) {
while (n <= 1) {

System.out.println("You did not enter a valid positive, greater than 1 integer. Please try again: ");
System.out.println();

}
}
}
return list;
}
}

这是主类(不起作用)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;


public class TestHailstoneSequence {

@SuppressWarnings("resource")
public static void main(String[]args){

Scanner input = new Scanner(System.in);

System.out.println("The Hailstone Sequence takes a number and if it odd it multiples it by 3 and adds 1,"
+ "\nit divides it by 2 and carries on until it reaches 1. \nPlease enter a positive number"
+ " (greater than 1) to generate the Hailstone Sequence: ");

int n = input.nextInt();

HailstoneSequence aHailstoneSequence = new HailstoneSequence(n);

System.out.println(Arrays.toString(aHailstoneSequence.list));

}
}

请帮助我了解如何打印结果

最佳答案

您将 getHailstoneSequence 方法声明为静态方法,如果您需要在另一个操作中进行打印,则应该调用它并将其存储到变量中,如下所示:

ArrayList<Integer> list = HailstoneSequence.getHailstoneSequence(n);
System.out.println(list);

关于java - 从单独的 Java 主类打印 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62419193/

27 4 0