【发布时间】:2015-12-04 16:17:44
【问题描述】:
我有以下程序要写:
数学中一个有趣(但尚未解决)的问题称为“冰雹数字”。这个数列是通过取一个初始整数,如果是偶数,除以 2。如果是奇数,乘以 3 并加 1。这个过程是重复的。
例如:初始值 10 产生:10、5、16、8、4、2、1、4、2、1... 初始值 23 产生:23、70、 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1...
请注意,这两个数字最终都会到达 4、2、1、4、2、1... 循环。
创建一个应用程序,为用户提供三种不同的方式来运行该程序。
选项 1:打印单个条目的冰雹编号及其长度
示例:输入> 10 10, 5, 16, 8, 4, 2, 1 长度7选项 2:打印从 4 到给定条目的所有冰雹编号
示例:输入> 6 4, 2, 1 长度 3 5, 16, 8, 4, 2, 1 长度 6 6, 3, 10, 5, 16, 8, 4, 2, 1 长度 9选项 3:打印出达到循环所需的最大迭代次数的数字,以及哪个起始数字产生从 4 到输入数字的最大值。
示例 : 输入> 6 最长: 6 长度: 9在编写此程序时,您必须实现以下方法...
/**
*
* @param num Number that a hailstone chain will be generated
* @param showNumbers true if list of numbers is shown to screen
* @return Count of the numbers in the num hailstone chain.
*/
private static int hailStone(int num, boolean showNumbers) {
// your code
}
这是我目前写的代码:
public static void main(String[] args) {
int a = getInt("Give a number: ");
System.out.print("How would you like to run the program? Option 1 prints hailstone numbers for a single entry and its length." +
"Option 2 prints all the hailstone numbers from 4 to a given entry. Option 3 prints the number with the maximum number" +
"of iterations needed to reach the 4, 2, 1 cycle.");
int option = console.nextInt();
boolean showNumbers = (option == 1 || option == 2);
hailStone(a, showNumbers);
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
private static void hailStone (int a, boolean showNumbers) {
if (showNumbers == true) {
if (a % 2 == 0) {
for (int i = 0; i < 50; i++) {
for (int j = 0; j <= i; j++)
a /= 2;
System.out.print(a + " ");
a *= 3;
a += 1;
System.out.print(a + " ");
}
} else {
for (int i = 0; i != a; i++) {
}
}
} else {
}
}
我觉得自己碰壁了,因为我不知道如何按照老师要求我们使用的方法来实施所有这些选项。另外,我似乎连基本的冰雹链都无法打印。帮忙?
【问题讨论】:
-
具体来说,您需要哪些帮助?我们无法为您解决全部问题。
-
“我似乎连基本的冰雹链都无法打印”我会先尝试让它工作。
标签: java loops if-statement for-loop methods