Java平均函数 [英] Java Average Functions

查看:453
本文介绍了Java平均函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的新手,我试图找出一个简单的平均函数.我写了一个平均3个整数的函数.现在,我希望能够使用任何集合类和任何数字类并获得平均值.问题在于这些类不能使用+或/来获取平均值.

I am new to programming and I am trying to figure out a simple average function. I have written a function to average 3 integers. Now I would like to be able to use any collection class and any number class and get the average. The problem is with these classes you can't use + or / to get the average.

所以我想知道是否有任何变通办法可以使用这两个类?

So I am wondering if there are any work-arounds to be able to use these two classes?

这是我的第一个有效的功能:

here is my first function that works:

package refresh;
import java.util.*;

public class Average {
public static void main( String args[]){

    int a, b, c;
    float average;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter First Number");
    a = scanner.nextInt();
    System.out.println("Enter Second Number");
    b = scanner.nextInt();
    System.out.println("Enter Third Number");
    c = scanner.nextInt();
    average = (float)(a+b+c)/3;
    System.out.println("The Average Is "+average );
}
 }

这是我到目前为止遇到的问题:

Here what I have so far for my problem:

package refresh;
import java.util.*;

public class Average {
public static void main( String args[]){

    Collection numbers;
    Number count;
    Number  average;

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter Numbers to be averaged");
    numbers = (Collection) scanner.match();
    count++;
    average = numbers/count;
    System.out.println("The Average Is "+average);
}
}

任何帮助都会很棒!感谢您的宝贵时间!

Any help would be great! Thanks for your time!

推荐答案

如果您不知道要尝试使用哪种数字,将String转换为数字(Scanner就是这么做的)是没有意义的.转换成.

It makes no sense to convert a String into a number (which is what Scanner does) if you don't know what kind of number you're trying to convert it into.

您几乎可以将任何数字表示为Double.如果需要任意精度,请使用BigDecimal.

You can represent pretty much any number as a Double. If you need arbitrary precision, use BigDecimal.

平均代码可以在Number接口上完全通用;只需使用doubleValue方法.如果您需要BigDecimal,那么它会更加复杂,您可能需要执行涉及instanceof的事情.

The averaging code can be fully generic over the Number interface; just use the doubleValue method. If you need BigDecimal, then it's more complicated and you probably need to do things involving instanceof.

这篇关于Java平均函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆