亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java,當輸入為空時如何中斷循環?

Java,當輸入為空時如何中斷循環?

慕田峪9158850 2023-07-13 17:46:40
這樣做的目的是讓用戶每行輸入一個數字,當用戶不再希望繼續時,他們應該能夠輸入一個空行,當發生這種情況時,程序應該給您一條包含最大數字的消息。問題是我無法用空行中斷循環。我不知道該怎么做。我檢查了其他問題以尋求解決方案,但找不到任何有幫助的內容。我也無法分配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);    }}
查看完整描述

2 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

這應該可以解決您的問題:


import java.util.Scanner;


public class StackOverflow {


    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;


        try {

            while(!scan.nextLine().isEmpty()){

                int num = Integer.parseInt(scan.nextLine());


                if(num > x) {

                    x = num;

                }

            }

        } catch (NumberFormatException e) {

            e.printStackTrace();

        }


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

        scan.close();

    }


}


查看完整回答
反對 回復 2023-07-13
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

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


    }

}



查看完整回答
反對 回復 2023-07-13
  • 2 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號