繁体   English   中英

如何在不使用任何循环的情况下无限期地向用户询问输入?

[英]How Do I Ask the User for An Input Indefinitely Without Using Any Loops?

我最近不允许在我的作业中使用任何循环,这让我很难过这个最新的作业。 我应该无限期地向用户询问一系列整数,直到他们输入非整数,然后通知他们最大的整数。 但是,以下代码仅接受单个输入:

public class GreatestNumber {
    public static void main(String[] args) {
        Scanner in= new Scanner(System.in);
        int a;
        int g=0;
        System.out.println("Enter several numbers. Enter a non-integer to end.");
        if(in.hasNext()){
        try{a=in.nextInt();
        g=Greatest(a); }
        catch (NumberFormatException e){
            System.out.println("Greatest number in that sequence is "+g);
        }}}
    public static int Greatest(int x){
        int g=0;
        if (x>g){
            g=x;
        }
        return g;
        }
    }

那是很多代码。 你可以使用递归。 greatest定义为使用Scanner ,检查int并使用Math.max(int, int)递归。 喜欢,

public static int greatest(Scanner in) {
    if (in.hasNextInt()) {
        return Math.max(in.nextInt(), greatest(in));
    }
    return Integer.MIN_VALUE;
}

然后调用它,你只需要像

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter several numbers. Enter a non-integer to end.");
    System.out.println("Greatest number in that sequence is " + greatest(in));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM