开发者社区> 问答> 正文

如何在不使用任何循环的情况下无限期要求用户输入?

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

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

问题来源:Stack Overflow

展开
收起
montos 2020-03-26 15:08:34 370 0
1 条回答
写回答
取消 提交回答
  • 那是很多代码。您可以使用递归。定义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));
    }
    

    回答来源:Stack Overflow

    2020-03-26 15:08:57
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载