どのように私は、任意のループを使用しない無期限の入力をユーザーに依頼しますか?

GreyishBlack:

私は、私は、この最新の割り当てに困惑していた、最近の私の割り当てのいずれかのループを使用することはできませんよ。私は、彼らが非整数を入力するまで、無期限に、一連の整数をユーザーに尋ねるの最大の整数を知らせることになっています。この次のコードは、しかし、唯一の単一の入力になります:

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=282176&siteId=1