入力が空の時にJavaは、どのようにループを切断するには?

Allnj:

これの目標は、ユーザーが行とするとき、ユーザーは、もはや彼らは、空行を入力することができるはず、それはプログラムを発生したとき、あなたがあなたの最大の番号のメッセージを与える必要があり続けたいごとに番号を入力させることです。

問題は、私は空行でループ断線することはできませんです。私はどのようにするかわかりません。私は解決策のための他の質問をチェックしましたが、私は助けた何かを見つけることができませんでした。私も割り当てることができませんscan.hasNextInt() == null....

私は、私は考えていないよという本に迅速かつ論理的な解決策があると確信しています。

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println(Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line));
        int x = 0;

        while(scan.hasNextInt()){
            int n = scan.nextInt();

            if (n > x){
               x = n;
            }
        }

        System.out.println("Largets number entered: " + x);

    }
}
Tanishqa Mahendru:
import java.util.*;

public class main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
        String str = scanner.nextLine();
        int x = 0;

        try {
            while(!str.isEmpty()){
                int number = Integer.parseInt(str);

                if (number > x){
                    x = number;
                }

                str = scanner.nextLine();
            }
        }
         catch (NumberFormatException e) {
             System.out.println("There was an exception. You entered a data type other than Integer");
         }

        System.out.println("Largets number entered: " + x);

    }
}

おすすめ

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