如何在Java中键入字符串以结束整数扫描过程 [英] How to type a string to end a integer Scanning process in Java

查看:35
本文介绍了如何在Java中键入字符串以结束整数扫描过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Scanner扫描任意数量的整数,然后获得平均值.在我停下之前,我想输入"END".

I would like to use Scanner to scan any number of integer then get the average. Before I stop, I would like to type "END".

以下代码具有: 线程主"中的异常java.util.InputMismatchException .那是因为我扫描的是字符串而不是int类型.

The code below has: Exception in thread "main" java.util.InputMismatchException error. That is because I scan a string rather than int type.

我应该如何解决这个问题?

How should I solve this problem?

谢谢

public static int scanaverage()
{
System.out.println("Enter any number, type 'END' to exit");
Scanner input = new Scanner(System.in);
int total=0; 
int count = 0;

while (!(input.nextLine().equals("END")))
{
total += input.nextInt();
count += 1;
}
return total / count;
}

推荐答案

您可以扫描整行并检查该行是否是这样的数字

You could just scan the whole line and check if the line is a number like this

public static int scanaverage() {
    System.out.println("Enter any number, type 'END' to exit");
    Scanner input = new Scanner(System.in);
    int total = 0;
    int count = 0;
    String line;
    do {
        line = input.nextLine();
        try {
            total += Integer.parseInt(line); // Cast the number, if it does not succeed catch the exception.
            count += 1;
        } catch(NumberFormatException e) {
            if(!line.equalsIgnoreCase("end")) { // Wrong input
                System.out.println("Wrong input, input another number or end");
            }
        }
    } while (!line.equalsIgnoreCase("end"));
    return total / count;
}

这篇关于如何在Java中键入字符串以结束整数扫描过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆