【问题标题】:Rerunning my main method after my boxPrint method在我的 boxPrint 方法之后重新运行我的 main 方法
【发布时间】:2016-09-09 18:37:31
【问题描述】:

您好,我正在尝试让它重新循环通过我的代码,但它似乎在打印框后就退出了:

import java.util.Scanner;

public class BoxPrint1 {   

    public static void main(String[] args)    
    {
        Scanner input = new Scanner(System.in);// create scanner object called input  
        // delcare variables

        int column;   
        int row;     

        System.out.printf("%nThis program prints a box");       // prompt user for input
        System.out.printf("%n Please enter # of columns (< 1 to exit):");
        column = input.nextInt();
        System.out.printf("%n Please enter # of rows (< 1 to exit):");
        row = input.nextInt();
        boxPrint(column, row);

        while(column > 0 && row > 0);  
        {    // calls boxPrint method and passes two arguments  
            // prompt user for input
            System.out.printf("%n Please enter # of columns (< 1 to exit):");
            column = input.nextInt();
            System.out.printf("%n Please enter # of rows (< 1 to exit):");
            row = input.nextInt();
        }   
    }// end main


    public static void boxPrint(int column, int row)
    {
        //insert nested for loops below
        for(int i = 0; i < row; i++) 
        {
            for(int j = 0; j < column; j++) 
            {
                    // prints * j times in a row
                System.out.printf("*");
            }
        System.out.println();
        } // end boxPrint method
    }   
    // end class BoxPrint1
}

这是我的代码,通常我会得到(它应该输出的内容)的输出





类似这样,但它不会重新循环到我的主要方法并再次要求输入?

【问题讨论】:

  • 在 main 方法的开头使用 while(true) 并在 // end main 之前关闭它。

标签: java loops methods


【解决方案1】:

将 main 方法更改为如下所示

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);// create scanner object called input
    // delcare variables

    int column;
    int row;

    System.out.printf("%nThis program prints a box");       // prompt user for input
    do {
        System.out.printf("%n Please enter # of columns (< 1 to exit):");
        column = input.nextInt();
        System.out.printf("%n Please enter # of rows (< 1 to exit):");
        row = input.nextInt();
        boxPrint(column, row);
    } while (column > 0 && row > 0);
}

【讨论】:

    【解决方案2】:

    这可能是因为您在 while 循环检查之后放置了一个分号。 它根本不会进入 while 循环来提示您再次输入输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-01
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2016-11-06
      • 2020-02-13
      • 1970-01-01
      相关资源
      最近更新 更多