所以我是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/