猿问

循环的递增符号

我正在创建一个要求我输入数字的方法,我会用星号打印出那个数字。例如,如果我输入数字 4 这应该打印出来:


*


**


***


****

代码:


public static void main(String[] args) 

    {

        Scanner in = new Scanner(System.in);

        System.out.println("Enter your number ");

        int number = in.nextInt();

        String numbah = Integer.toString(number);

        String substring = numbah.substring(0);



        if(number < 0)

        {

            System.out.println("Bye bye!");

            System.exit(0);

        }


        for(int i = 0; i < number; i ++)

        {

            System.out.println("*");

        }

    }

}

我只是在每行增加符号时遇到问题。


慕码人8056858
浏览 141回答 3
3回答

回首忆惘然

或者更简单的版本:for(int i = 1; i <= number; i ++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int j = 1; j <= i; j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }添加内连接

慕工程0101907

Java 11 允许重复方法..for(int&nbsp;i&nbsp;=&nbsp;1;&nbsp;i&nbsp;<&nbsp;=number;&nbsp;i&nbsp;++).&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println("*".repeat(i)); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}

鸿蒙传说

尝试使用 java 11 中的重复public static void main(String[] args)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Scanner in = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter your number ");&nbsp; &nbsp; &nbsp; &nbsp; int number = in.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; String numbah = Integer.toString(number);&nbsp; &nbsp; &nbsp; &nbsp; String substring = numbah.substring(0);&nbsp; &nbsp; &nbsp; &nbsp; if(number < 0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Bye bye!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.exit(0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < number; i ++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("*".repeat(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;}或来自 java 1.5+&nbsp;System.out.println(new String(new char[i]).replace("\0","*");正如其他人所说,您可以创建一个字符串变量并在每个循环中连接一个 *
随时随地看视频慕课网APP

相关分类

Java
我要回答