Java 当用户输入字符串而不是整数时,如何防止应用程序在计算n个数字的平均值时崩溃
这是我的密码Java 当用户输入字符串而不是整数时,如何防止应用程序在计算n个数字的平均值时崩溃,java,Java,这是我的密码 /* * 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; /**
/*
* 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;
}
}
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
包javaapplication2;
导入java.util.Scanner;
/**编写一个java程序,将三个数字作为输入并打印这些数字的平均值
*
*
*@作者takenoLAB
*/
公共课平均分{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
System.err.println(“输入以“.”分隔的数字);
字符串n=input.nextLine();
系统输出打印(“这是您的平均值”+cal(n));
}
公共静态双cal(字符串数据){
字符串[]数据=data.split(“,”);
双tota=0;
双avr=0;
试一试{
对于(int i=0;i仅当遇到整数时才使用此选项,将其添加到总计并增加计数器。结果将取决于实际存在的整数数量
public static double cal(String data) {
String[] datas = data.split(",");
double tota = 0;
double avr = 0;
int count = 0;
for (String s: datas)
{
try{
tota += Integer.parseInt(s);
count++;
} catch(NumberFormatException ne)
{
}
}
avr = tota / count;
return avr;
}
输出:
enter your numbers separated by ,
5,2,3,a,5
4
here is your average 3.75
您可以使用方法。例如:
if(StringUtils.isNotBlank(s) && StringUtils.isNumeric(s)){
tota += Integer.parseInt(s);
}
因此,它将只添加来自用户的有效输入,而忽略所有其他无效数据(空白、空格、非数字的字符串)而且不会发生异常。它只打印0.0
,那么您面临的问题是什么?您想退出程序完全忽略无效输入,还是在平均计算中跳过这些输入?非常感谢,它工作得很好。您能接受作为答案并关闭它吗?我们也不应该使用datas.length作为除数,因为它可以有非整数值too@SabareeshMuralidharan这与我的答案无关。我回答OP的问题。其次,你写的是错误的,avr
将始终是一个double
。OP应该检查的是data.length
是否为0,这将导致当前的例外。慢慢来,再看一次我的评论w.r.t to OP的代码