在java中重复一个程序 [英] repeating a program in java

查看:50
本文介绍了在java中重复一个程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试重复这个程序,但是当我这样做时,我不断收到错误消息.我之前重复过,但它要求在每一行星号后重复.这是我目前所拥有的:

I've been trying to repeat this program, but when I do, I keep getting errors. I repeated it before, but it asked to repeat after every row of asterisks. This is what I have so far:

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()));
  }

}

推荐答案

我猜你想重复上面的逻辑 - 对吗?

I am guessing that you want to repeat the above logic - right?

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

If this is the case then do not close your scanner

还有你的 while 格式错误.

Also your while is wrongly formatted.

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

在这种情况下,将 ; 放在最后会导致无限循环.

Having the ; on the end will cause an endless loop in this case.

试试

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 ();

这篇关于在java中重复一个程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆