java如何防止应用程序在用户输入字符串而不是整数时计算n个数的平均值时崩溃
这是我的密码
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
import java.util.Scanner;
/**write a java program that take three Numbers as input and print the average of the numbers
*
*
* @author takenoLAB
*/
public class Average {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.err.println("enter your numbers separated by ,");
String n = input.nextLine();
System.out.print("here is your average "+cal(n));
}
public static double cal(String data){
String [] datas=data.split(",");
double tota=0;
double avr=0;
try{
for (int i=0;i<datas.length;i++){
tota+=Integer.parseInt(datas[i]);
}
avr = tota/datas.length;
}
catch(Exception err){}
return avr;
}
}
# 1 楼答案
只有在遇到整数时才使用此选项,将其添加到总数并增加计数器。结果将取决于实际存在的整数数量
输出:
# 2 楼答案
可以使用StringUtils.isNumeric()方法。例如:
因此,它将只添加来自用户的有效输入,并忽略所有其他无效数据(空白、空格、非数字的字符串),并且不会发生异常