编写一个称为平均值的类,该类可用于计算多个整数的平均值。它应包含以下方法:
发出错误消息,如果第二个参数小于第一个参数,则返回零。否则,该方法应返回该范围内(含)的整数平均值。实现该类并编写程序以测试其方法并提交源代码(.java文件)。
我被困在第三部分,我什至不真正理解规定。我会使用浮点/双精度吗?这是我到目前为止的程序:
import java.util.Scanner; public class Average { public static void main(String[] args) { int numb1, numb2, numb3, userInput; System.out.println("Enter '2' if you wish to average two numbers enter '3' if you wish to average 3."); Scanner keyboard = new Scanner(System.in); userInput = keyboard.nextInt(); if (userInput == 2){ System.out.println("Enter two numbers you'd like to be averaged."); numb1 = keyboard.nextInt(); numb2 = keyboard.nextInt(); Average ave = new Average(); System.out.println("The average is: " + ave.average(numb1, numb2)); System.exit(1); } if(userInput == 3){ System.out.println("Enter three numbers you'd like to be averaged."); numb1 = keyboard.nextInt(); numb2 = keyboard.nextInt(); numb3 = keyboard.nextInt(); Average ave = new Average(); System.out.println("The average is: " + ave.average(numb1, numb2, numb3)); System.exit(1); } } public static int average (int num1, int num2) { return (num1 + num2) / 2; } public static int average (int numb1, int numb2, int numb3){ return (numb1 + numb2 + numb3) / 3; } }
并不是真的在这里做作业,但是由于我已经在这里,所以范围是最大和最小数字之间的差。
public int returnRange(int first, int second) { if(first > second) return first-second; else return second-first; }
为了使事情变得更容易…
public double returnAverage(int...numbers) { for(int i = 0; i < numbers.length(); i++) { total += numbers; } return total/numbers.length(); } public int returnRange(int...numbers) { int holder = 0; int highest; int lowest; for(int i = 0; i < numbers.length(); i++) { if(numbers[i] > holder) { holder = numbers[i]; } highest = holder; for(int i = 0; i < numbers.length(); i++) { if(numbers[i] < holder) { holder = numbers[i]; } } lowest = holder; return highest-lowest; }
最后两种方法未经测试,但是从经验来看,应该可以正常工作。这些方法具有用于参数的数组,因此您可以根据需要执行任意多个数字。