在java中重复一个程序

时间:2014-08-13 01:07:42

标签: java repeat

我一直试图重复这个程序,但是当我这样做时,我一直都会遇到错误。我之前重复过,但它要求在每一行星号后重复。这就是我到目前为止所做的:

import java.util.Scanner;

public class Pyramid 
{

//Displaying a Pyramid
public static void main(String[] args) 
{
  Scanner scanner = new Scanner(System.in);
  //Get user input = number of rows to print in a pyramid
  System.out.print("Enter an integer for the number of rows: ");
  int userInput = scanner.nextInt();
  scanner.close();

  int myLevel;
  int i, j , k;

  myLevel = userInput;

  for (i = 1; i <= myLevel; i++) {

  for (k =1; k <= myLevel-i; k++)

  System.out.print(" ");

  for (j = k+1; j <=myLevel; j++) 

  System.out.print( "*");
  for(int l=myLevel;l>k-1;l--)
  System.out.print( "*");

  System.out.println("");
   System.out.println("You want to continue : (Y/N) ");
    } while("Y".equalsIgnoreCase(scanner.next().trim()));
  }

}

2 个答案:

答案 0 :(得分:1)

我猜你想重复上述逻辑 - 对吧?

如果是这种情况,请不要关闭scanner

你的格式错误。

while("Y".equalsIgnoreCase(scanner.next().trim()));

在这种情况下,最后使用;会导致无限循环。

尝试

private static void myMethod(Scanner scanner) {
      //Get user input = number of rows to print in a pyramid
      System.out.print("Enter an integer for the number of rows: ");
      int userInput = scanner.nextInt();

      int myLevel;
      int i, j , k;

      myLevel = userInput;

      for (i = 1; i <= myLevel; i++) {

      for (k =1; k <= myLevel-i; k++)

      System.out.print(" ");

      for (j = k+1; j <=myLevel; j++) 

      System.out.print( "*");
      for(int l=myLevel;l>k-1;l--)
      System.out.print( "*");

      System.out.println("");

}

称之为

    Scanner scanner = new Scanner(System.in);

    do {
        myMethod (scanner);
        System.out.println("You want to continue : (Y/N) ");
    } while("Y".equalsIgnoreCase(scanner.next().trim()));   

    scanner.close ();

答案 1 :(得分:0)

代码末尾有一个空的while语句。您正在尝试阅读不存在的输入。您需要将整个程序封装在一个循环中。在输入之前,您不需要循环。

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);



do{
          //Get user input = number of rows to print in a pyramid
          System.out.print("Enter an integer for the number of rows: ");
          int userInput = scanner.nextInt();

          int myLevel;
          int i, j , k;

          myLevel = userInput;

          for (i = 1; i <= myLevel; i++) {

          for (k =1; k <= myLevel-i; k++)

          System.out.print(" ");

          for (j = k+1; j <=myLevel; j++) 

          System.out.print( "*");
          for(int l=myLevel;l>k-1;l--)
          System.out.print( "*");

          System.out.println("");
            } 
          System.out.println("You want to continue : (Y/N) ");
          } while("Y".equalsIgnoreCase(scanner.next().trim()));
    }

您也关闭了扫描仪,因此您无法重复使用它。