这是一个家庭作业问题,所以我需要帮助,而不是答案。
我正在尝试创建2个三角形的数字基于用户输入的数字。
"Enter a number between 2-9: "3"
1
12
123
1
21
321IE2:
"Enter a number between 2-9: "5"
1
12
123
1234
12345
1
21
321
4321
54321我已经完成了第一个三角形。但是当我添加我的嵌套循环时,它会用从嵌套循环得到的数字弄乱我的第一个三角形。它还将所有数字放在一条直线上。我尝试过不同nest循环的变体,甚至尝试过修改StringBuilder,但仍然不成功。到目前为止,我在代码中的代码如下:
import java.util.Scanner;
public class NestedLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a Number between 2-9: ");
int width = input.nextInt();
String r = "";
for (int i = 1; i <= width; i++)
{
r = r + i;
System.out.println(r);
}
}
}再说一次,我在寻求帮助/理解,而不仅仅是一个答案。
发布于 2013-02-17 11:51:14
试一试
int width = 5;
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// print numbers from 1 to current line number
for (int n = 1; n <= line; n++) {
System.out.print(n);
}
// end of line
System.out.println();
}
// add empty line between triangles
System.out.println();
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// printing padding spaces, number of spaces = with - line number
int nSpaces = width - line;
for (int i = 0; i < nSpaces; i++) {
System.out.print(" ");
}
// print numbers from number of current line to 1
for (int n = line; n >= 1; n--) {
System.out.print(n);
}
// end of line
System.out.println();
}发布于 2013-02-17 12:01:36
问题的第二部分有两个方面。
- You could do this by adding the numbers at the other end.
- You could do this by reversing the strings.
- You could do this by adding the required number of spaces to the left end of the string.
- You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)
或者,可以在字符数组或字符串生成器中生成字符串,而不是使用字符串连接。
“诀窍”是弄清楚你要用什么策略……在你开始裁剪代码之前。
发布于 2013-02-17 11:29:34
您需要使用队列。例如:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html
对数字进行编码,直到达到最大值,然后开始计算它们。
当你离开队列时,你需要应用相反的方法
Queue<String> q = new LinkedList<String>();
for (int i = 1; i <= width; i++)
{
r = r + i;
q.add(r);
System.out.println(r);
}
while(!q.isEmpty()){
String j = q.remove();
//reverse j
System.out.println(reverse(j));
}我把反转的部分留给你去做:)
https://stackoverflow.com/questions/14917674
复制相似问题