【发布时间】:2019-11-09 12:46:21
【问题描述】:
当我输入任何数量的数字时,它给了我错误的平均值我不知道为什么我尝试了很多方法但平均值仍然无法正常工作 我做错了什么得到错误的结果? 任何建议..
import java.util.Scanner;
public class Assignment_Help2 {
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String[] department = new String[5];
int[] employeesno = new int[5];
String [] address = new String[5];
int index;
index = 0;
int totalentered = 0;
String temp;
// One loop to enter all information
//INPUT LOOP
for (index = 0; index < 5; index++)
{
System.out.print("Enter a department or stop ..: ");
department[index] = keyboard.nextLine();
if (department[index].equals("stop"))
{
break;
}
System.out.print("employees_no: ");
temp = keyboard.nextLine();
// convert string to a number & then store it as integer in the array
employeesno[index] = Integer.valueOf(temp);
System.out.print("Enter address: ");
address[index] = keyboard.nextLine();
totalentered++;
} //END OF FOR LOOP
System.out.println("==================================");
System.out.println(String.format("%-20s", "department")+
String.format("%-18s", "no_employees")+
String.format("%-20s", "Address"));
// Another separate loop to display the information stored in arrays
//OUTPUT LOOP
for (index = 0; index < totalentered; index++)
{
System.out.println(String.format("%-20s", department[index]) +
String.format("%-18d", employeesno[index])+
String.format("%-20s", address[index]));
}
int sum1=0;
double average;
for(int l=0; l <employeesno.length ; l++)
{
sum1 += employeesno[l];
} average= sum1/employeesno.length;
System.out.println("aver= "+average);
keyboard.close();
}
}
【问题讨论】:
-
也许您还没有,但是当涉及到存储未知数量的元素时,您通常使用
List实例而不是 Java 中的低级数组。你会使用一个类Department和属性name、employees和address,所以你可以只使用一个列表。 -
我是学生,刚刚开始使用 java,它是我作业的一部分,我们已经完成了学习列表,但我尝试创建新方法并将其命名为 average 仍然给我不同的结果。感谢您的回复
-
这是因为尽管列表包含
size()方法,但您的计数方式不同。但是,您忘记了循环中计算平均值(以及随后的除法)的变量。