有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;
    }
    
   
    
}

共 (2) 个答案

  1. # 1 楼答案

    只有在遇到整数时才使用此选项,将其添加到总数并增加计数器。结果将取决于实际存在的整数数量

    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
    
  2. # 2 楼答案

    可以使用StringUtils.isNumeric()方法。例如:

    if(StringUtils.isNotBlank(s) && StringUtils.isNumeric(s)){
         tota += Integer.parseInt(s);
    }
    

    因此,它将只添加来自用户的有效输入,并忽略所有其他无效数据(空白、空格、非数字的字符串),并且不会发生异常