Bluej/Java循环?

Bluej/Java loop?

我还是 Java 的新手,我正在为 class 在 Bluej 中学习。我的 class 正在做一个有趣的小程序来学习,我想知道...我怎样才能让程序通过脚本(或重新启动)本身?对不起,如果你得到了很多,但我一直在寻找一个多小时的答案但没有成功。我还需要它用于其他一些程序,哈哈

代码如下:

import java.util.Scanner;
public class TriangleFirst
{

    public static void main (String [] args) {
          System.out.println ("\f");
          Scanner SC = new Scanner(System.in);
          int numbstars;


          System.out.println ("How large would you like your (sideways) pyramid to be? (insert a number)");
          numbstars = SC.nextInt();
        for (int i=1; i<= numbstars; i++) {
                for (int j=0; j < i; j++) {
                    System.out.print ("*");
                }
                //generate a new line
                System.out.println ("");
            }

        for (int i= numbstars-1; i>=0; i--) {
                for (int j=0; j < i; j++) {
                    System.out.print ("*");

                }
                //generate a new line
                System.out.println ("");
            }
    }
}

要重复一些 Java 代码,请将其包含在 while 循环中。

do {
    System.out.println("How large …");
    …
} while (askAgain());

askAgain 是一个单独的方法,应该如下所示:

public class TriangleFirst {
    Scanner input = new Scanner(System.in);

    private boolean askAgain() {
        System.out.println("Again?");
        return input.nextLine().toLowerCase().startsWith("y");
    }
}

因为您应该只有一个 Scanner 作为输入,删除 SC 变量并将其替换为 input

我不完全确定我理解你的问题,但如果你只想让程序在结束后继续 运行,那么你需要做的就是插入一个while 循环。

import java.util.Scanner;
public class TriangleFirst {

    public static void main (String [] args) {
        while(true) {
            //your code goes here
        }
    }
}

这里的想法是一遍又一遍地做某事,直到你被告知否则。您已经在 for 循环中接触过这个想法。 while 循环是另一种需要了解的循环。 while 循环定义如下:

  while(condition is true) {
    // do something
 }

它会一遍又一遍地执行它里面的所有代码,直到你通过break;强制它停止或者条件是false(改变一个布尔值,一个数字低于0,你有什么条件)。 while 循环的更高级形式是 do while 循环。 do while 看起来像这样:

  do {
    // do something
 } while(condition is true);

这里的区别是do while总是执行一次。之后它将评估条件,然后再决定是否 运行 。 while 循环可能永远不会执行!这一切都取决于条件。

现在,根据您的情况,您可以进行方法调用。所以:

do {
  // stuff
 } while (askTheUser()); //askTheUser returns a Boolean.

甚至

do {
  // stuff
 } while (getNumber() > n);

(注意,while 的工作方式相同。)

不管最终结果应该是布尔值。您的星号打印和用户输入的星号可以是单独的方法调用(通常将逻辑分离到方法调用中以使调试更容易是个好主意)。所以...

while (askUserToPlayAgain()) {
    int n = getInput();
    printStars(n);

}

应该会让您对如何实施它有一个很好的了解。