如何将函数实现到main中

How to implement the function into the main

所以我有一个工作代码,它询问用户矩形的高度和宽度,然后以星号 (*) 输出矩形。

现在我想实现一个函数 public static int askPositiveInteger(String question, String messageIfError) {...},它使用scanner.hasNextInt()(检查整数)和scanner.next()(扔掉任何废话用户写道)。

该函数应该使用消息 question 向用户询问一个正整数。如果输入错误,它会打印错误消息 messageIfError 并再次询问。

我写了函数:

public static int askPositiveInteger(String question, String messageIfError) {
    int num = -1;
    do {
        System.out.print("Please enter a positive integer number: ");
        if (scan.hasNextInt()) {
            num = scan.nextInt();
        } else {
              System.out.println("I need an int, please try again.");
              scanner.next();
          }
    } while (num <= 0);
}

但我不确定如何将其实现到我的代码中:

public static void main(String[] args) {

    int height, width, i, j;

    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter the height of the rectangle: ");
    height = scanner.nextInt();

    System.out.print("Enter the width of the rectangle: ");
    width = scanner.nextInt();

    for(i = 1; i <= height; i++){
        for(j = 1; j <= width;j++){
            System.out.print("*");
        }
    System.out.print("\n");
    }
scanner.close();
}

您的函数并没有真正使用参数 String questionString messageIfError。您只需换掉

即可将它们集成到您的函数中

System.out.print("Please enter a positive integer number: ");System.out.println("I need an int, please try again.");

System.out.print(question);System.out.println(messageIfError);.

这将导致:

public static int askPositiveInteger(String question, String messageIfError, Scanner scan) {
    int num = -1;
    while(num <= 0){
        System.out.print(question);
        num = scan.nextInt();
        if(num <= 0){
            System.out.println(messageIfError);
        }
        scan.nextLine();
    }
    return num;
}

我还更改了功能,您可以使用现有的扫描仪并扫描给定的扫描仪。

在您的主程序中实现这个新功能如下所示:

public static void main(String[] args) {

    int height, width;
    Scanner scan = new Scanner(System.in);

    height = askPositiveInteger("Enter the height of the rectangle: ","I need an int, please try again.", scan);
    System.out.println("h = " + height);
    width = askPositiveInteger("Enter the width of the rectangle: ","I need an int, please try again.", scan);
    scan.close();

    for(int i = 1; i <= height; i++){
        for(int j = 1; j <= width;j++){
            System.out.print("*");
        }
        System.out.print("\n");
    }
}

你大概是这么想的吗?