如何告诉这个Java方法在某种条件下再次执行自己?

时间:2015-06-05 00:50:20

标签: java stdout stdin

请参阅此UVa OJ问题:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=27&page=show_problem&problem=2595

它正在为一个测试用例工作。但是,没有给出测试用例数量的输入,这意味着程序应该知道何时继续以及何时仅通过读取问题变量的输入来停止

我考虑使用scanner.hasNextLine()方法作为条件;如果它是真的,重新开始,但我不知道该怎么做。任何线索?

public static void main(String[] args) {
    Scanner scanner = new Scanner (System.in);
    int N = scanner.nextInt();
    int B = scanner.nextInt();
    int H = scanner.nextInt();
    int W = scanner.nextInt();
    int [] priceArray = new int [H];
    int [] availableBeds = new int [W];
    int cheapestStay = 999999999;
    for (int i=0; i<H; i++){
        priceArray[i] = scanner.nextInt();

        for (int j=0; j<W; j++){
            availableBeds[j] = scanner.nextInt();
            if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
                cheapestStay = priceArray[i]*N;
            }

        }

    }

    if (cheapestStay != 999999999){
        System.out.println(cheapestStay);
    }else{
        System.out.println("stay home");
    }
    /*if (!scanner.hasNextLine)
        repeat*/
}

3 个答案:

答案 0 :(得分:1)

只要hasNextLine()评估为true,就可以使用while循环重复主方法的说明。

public static void main(String[] args) {
    while(scanner.hasNextLine()){
        ...
    }
}

答案 1 :(得分:0)

您可以将main(...)方法中的所有代码包装到while(scanner.hasNextLine())循环

答案 2 :(得分:0)

这是do-while

的最佳用法
public static void main(String[] args) {
    Scanner scanner = new Scanner (System.in);
    do {

        int N = scanner.nextInt();
        int B = scanner.nextInt();
        int H = scanner.nextInt();
        int W = scanner.nextInt();
        int [] priceArray = new int [H];
        int [] availableBeds = new int [W];
        int cheapestStay = 999999999;
        for (int i=0; i<H; i++){
            priceArray[i] = scanner.nextInt();

            for (int j=0; j<W; j++){
                availableBeds[j] = scanner.nextInt();
                if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
                    cheapestStay = priceArray[i]*N;
                }

            }

        }

        if (cheapestStay != 999999999){
            System.out.println(cheapestStay);
        }else{
            System.out.println("stay home");
        }
        /*if (!scanner.hasNextLine)
            repeat*/
    } while (scanner.hasNextLine());
}