Java 使用循环的模式

Java 使用循环的模式,java,Java,我必须做一个循环来读取用户的输入(假设他的输入是5),所以输出应该如下所示:- * ** *** **** ***** **** *** ** * intx; //输入1-20之间三角形的大小 扫描仪=新的扫描仪(System.in); System.out.println(“输入从1到20的三角形大小:”); x=scanner.nextInt(); 对于(inti=0;i以下代码打印三角形,假设用户输入10 for (int i = 0; i < 10; i++){ for

我必须做一个循环来读取用户的输入(假设他的输入是5),所以输出应该如下所示:-

*
**
***
****
*****
****
***
**
*

intx;
//输入1-20之间三角形的大小
扫描仪=新的扫描仪(System.in);
System.out.println(“输入从1到20的三角形大小:”);
x=scanner.nextInt();

对于(inti=0;i以下代码打印三角形,假设用户输入10

for (int i = 0; i < 10; i++){
    for (int j = 0;j < i;j++ )
    System.out.print('x');
    System.out.println();
}
for (int i = 10; i > 0; i--){
    for (int j = 0; j < i;j++)
    System.out.print('x');
    System.out.println();
}
for(int i=0;i<10;i++){
对于(int j=0;j0;i--){
对于(int j=0;j

在代码中,排除了第二个for循环,在该循环中i递减。

使用三元运算符的示例。如果x大于i,则增加j

int x = 5, j=0;

for (int i = 0; i <= x*2; i++) {
    j= (x>i)? ++j:--j;   // u can use if else also
    for (int y = 0; y < j; y++) {
        System.out.print(" *");
    }
    System.out.println("");
}

这看起来像是家庭作业……你最好努力完成它,因为这是一个相当琐碎的问题要解决。我不明白你为什么要打印空白。对于那种“钻石”来说,这不是必要的。这里不需要嵌套循环。请使用两个单独的循环。@wjohnsto实际上我并不想让别人帮我解决这个问题。我只是想得到帮助和提示来帮助我解决这个问题,我同意最好在整个过程中努力解决。谢谢你的帮助advise@Violetx你接受答案,如果他们帮了你
的忙,你就投赞成票运气好。
用什么?你已经解决了整个作业。这里的OP没什么可做的。谢谢你的帮助和评论。这真的帮助了我,我更改了你的部分答案以匹配我要解决的问题,非常感谢。我以前没有使用过打印线方法,但我想我会学会如何使用它,谢谢你的回答ne方法就是前面写的函数:)这是一个很大的帮助谢谢你回答我的问题我真的很感激!
int x = 5, j=0;

for (int i = 0; i <= x*2; i++) {
    j= (x>i)? ++j:--j;   // u can use if else also
    for (int y = 0; y < j; y++) {
        System.out.print(" *");
    }
    System.out.println("");
}
 *
 * *
 * * *
 * * * *
 * * * * *
 * * * * * *
 * * * * *
 * * * *
 * * *
 * *
 *
import java.util.Scanner;

public class Triangle {
    public static void printLine(int n) {
        for(int i = 0; i < n; i++) System.out.print("*");
        System.out.print("\n");
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner (System.in);
        System.out.println("Enter size of triangle");
        int x = scanner.nextInt ();

        for(int i = 0; i < x; i++) {
            printLine(i);
        }

        for(int i = x; i > 0; i--) {
            printLine(i);
        }
    }   
}
Enter size of triangle
5

*
**
***
****
*****
****
***
**
*