1

大家好,我只是在为自己做一些阅读以学习 Java,并遇到了这个问题,目前被卡住了。

我需要根据用户给出的输入打印出一系列数字。例如,如果输入 = 5,则输出应如下所示

@1@22@333@4444@55555

    import java.util.*;

public class ex5{
        public static void main(String[] args){
                Scanner kb = new Scanner(System.in);
                System.out.println("Please type a #: ");

                int input = kb.nextInt();

                for(int i=0;i<input;i++){
                        if(input==1){
                                System.out.print("@1");
                        }
                        if(input==2){
                                System.out.print("@1@22");
                        }
                }

        }
}

这似乎不起作用,因为这是我得到的输出

请输入 #: 2 @1@22@1@22

我现在不确定要在 for 循环中放什么,而且我认为我在这里也没有很好地使用 for 循环...

有什么帮助吗?

4

6 回答 6

2

你需要一个嵌套的for循环来解决这个问题。

于 2012-06-06T22:33:22.693 回答
2

是的,这不是你想要的方式。您将要在 for 循环中构建字符串。

从一个新字符串开始

String s = "";

循环时,添加到该字符串。

for(int i=1;i<=input;i++){
     s += @;
     for(int j=0; j<i; j++) {
         s+=i;
     }
 }
于 2012-06-06T22:33:32.590 回答
2
    for (int i=1; i<=5; i++){
        System.out.print("@");
        for (int j=1; j<=i; j++) System.out.print(i);
    }

出去

@1@22@333@4444@55555
于 2012-06-06T22:35:15.987 回答
1

您需要使用嵌套for循环。

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.println("Please type a #: ");

    int input = kb.nextInt();

    for (int i = 1; i <= input; i++) {
        System.out.print("@");
        for (int k = 0; k < i; k++) {
            System.out.print(i);
        }
    }
}
于 2012-06-06T22:34:22.930 回答
1

这是因为您正在检查 if 语句中的数字 1 和 2。它是硬编码的,只检查这两个数字,一旦超过你有 if 语句的值,它就不起作用

您要做的是输出迭代器的值(在您的情况下为 i)i 次(提示,您可以在大循环中使用另一个循环),然后在字符串末尾添加一个 @ 符号。

我会尽量不给你任何代码,这样你就可以自己学习,但请随时提出更多问题。

于 2012-06-06T22:37:39.410 回答
0

您正在尝试打印给定的数量 - 给定的次数?然后你需要两个循环 - 用于迭代数字的外部循环和内部 - 用于迭代-倍给定的数字。

它会是这样的:

for(int i = 0; i < input; ++i) {
    System.out.print("@");
    for(int j = 0; j < i; ++j) {
        System.out.print(i);
    }
}
于 2012-06-06T22:35:22.547 回答