我想在方法中使用ArrayList来使用Hailstone序列(http://plus.maths.org/content/mathematical-mysteries-hailstone-sequences),并使用该方法在用户输入数字后打印出所有步骤。这就是我现在所拥有的:
public static ArrayList<Integer> getHailstonSequence(int n){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(n);
while(n != 1){
if(n%2 == 0){
System.out.print(n + " is even so I take half ");
n = n/2;
System.out.println(n);
} else{
System.out.print(n + " is odd so I make 3n+1 ");
n = (n*3)+1;
System.out.println(n);
}
}
return getHailstonSequence(n);
}
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your number?");
int n = keyboard.nextInt();
}
谢谢!
对于任何误解,我们深表歉意。
我要做的是从用户创建一个程序编号,然后显示该编号的Hailstone序列。练习假设使用Arraylist。 再次抱歉任何误解,我不是故意让任何人生气。
答案 0 :(得分:3)
public class Test {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your number?");
int n = keyboard.nextInt();
ArrayList<Integer> result = getHailstonSequence(n);
System.out.println(result);
}
public static ArrayList<Integer> getHailstonSequence(int n) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(n);
while (n != 1) {
if (n % 2 == 0) {
System.out.print(n + " is even so I take half ");
n = n / 2;
System.out.println(n);
}
else {
System.out.print(n + " is odd so I make 3n+1 ");
n = (n * 3) + 1;
System.out.println(n);
}
numbers.add(n);
}
return numbers;
}
}