java - 在同一 Scanner 变量中使用整数/ double 和字符串

标签 java

所以我是Java编程的新手,来自Python,并且有一些概念我不太理解。

我正在编写一个程序,允许用户输入任意数量的数字,并且该程序应该输出所有数字的平均值。我使用 while 循环来根据用户的需要多次循环输入,但我需要一种退出循环的方法,以便程序可以继续计算所有输入的平均值。我决定,如果用户输入“=”符号而不是数字,那么程序将跳出循环,但由于 Scanner 变量正在寻找 double 值,并且“=”符号不是数字,所以我必须将其设为字符串。但由于扫描仪正在寻找 double 值,因此程序在遇到“=”时会抛出错误。

如何让程序在用户输入“=”时退出循环?我知道我可以允许用户输入一个打破循环的数字,但如果它是一个现实世界的程序并且用户输入了一个数字,那么在计算平均值时它会将该数字与之前的数字一起计算。到目前为止我的代码如下:

import java.util.Scanner;
// imports the Scanner class

public class Average{
    public static void main(String[] args){
        double num, total = 0, noOfInputs = 0, answer;
        Scanner scanner = new Scanner(System.in);

        while(true){
            System.out.print("Enter number: ");
            //Prompts the user to enter a number

            num = scanner.nextDouble();
            /*Adds the number inputted to the "num" variable. This is the
            source of my problem*/

            if(num.equals("=")){
                break;}
            /*The if statement breaks the loop if a certain character is
            entered*/

            total = total + num;
            //Adds the number inputted to the sum of all previous inputs

            noOfInputs++;
            /*This will be divided by the sum of all of the numbers because
              Number of inputs = Number of numbers*/
        }

        answer = total / noOfInputs;
        System.out.print(answer);

        }
}

最佳答案

有几种方法可以做到这一点。

您可以将每个数字作为字符串读取,然后如果它是数字,则解析它以获取值。

Integer.parseInt(String s)

或者您可以检查接下来会发生什么并相应地阅读:

while (scanner.hasNext()) {
                if (sc.hasNextInt()) {
                   int a = scanner.nextInt();
                } else if (scanner.hasNextLong()) {
                   //...
                }
}

或者您可以捕获InputMismatchException,然后从那里开始工作。

try{
  ...
} catch(InputMismatchException e){
  //check if  '=' ...
}

关于java - 在同一 Scanner 变量中使用整数/ double 和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39937887/

相关文章:

java - 全局变量在 Intent 之后始终为空

java - 使用 ScheduledThreadPool 并行执行

java - Selenium WebDriver 中使用 XPath 从子节点遍历到祖先节点

java - 如何使用 java util 日志框架以特定格式为每条记录创建日志文件

java - 从 JPMML 模型的 InputField 获取实际字段名称

java - 获取 Int 的后三位

java - 为什么一些 Android 代码在以前的 API 级别上工作而不是应该的?

java - 使用对象数组对 Java 进行堆排序

java - Spring MVC/JSP。如何创建带有国家/地区列表的多语言组合?

java - 如何在一项作业执行中停止 Spring 编写器