为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信