[英]How do I get the numbers in a String and then calculate the average of them?
[英]How do I calculate the average by using the get method for class objects?
我想獲得員工的平均服務年限。 當我在下面鍵入代碼並運行應用程序時,它崩潰了。 我不知道該怎么辦,所以我暫時將其注釋掉。 還要注意,我只希望使用String格式方法將平均值放在兩位小數位。 導致崩潰的代碼如下所示:
try
{
//Create an URL object that read urlfile
URL file_url = new URL(urlfile);
//try to open the file from the web
Scanner fsc = new Scanner(file_url.openStream());
//Read the data value from the file into each Employee object
nm = fsc.nextLine();
e1.setName(nm);
id = fsc.nextLine();
e1.setId(id);
s = fsc.nextDouble();
fsc.nextLine();
e1.setSalary(s);
of = fsc.nextLine();
e1.setOffice(of);
ex = fsc.nextLine();
e1.setExtension(ex);
y = fsc.nextInt();
fsc.nextLine();
e1.setYearsOfServ(y);
nm = fsc.nextLine();
e2.setName(nm);
id = fsc.nextLine();
e2.setId(id);
s = fsc.nextDouble();
fsc.nextLine();
e2.setSalary(s);
of = fsc.nextLine();
e1.setOffice(of);
ex = fsc.nextLine();
e2.setExtension(ex);
y = fsc.nextInt();
fsc.nextLine();
e2.setYearsOfServ(y);
nm = fsc.nextLine();
e3.setName(nm);
id = fsc.nextLine();
e3.setId(id);
s = fsc.nextDouble();
fsc.nextLine();
e3.setSalary(s);
of = fsc.nextLine();
e1.setOffice(of);
ex = fsc.nextLine();
e3.setExtension(ex);
y = fsc.nextInt();
fsc.nextLine();
e3.setYearsOfServ(y);
//Display all data for each employee (up to three)
tv.setText("Employee 1:\n" + e1.getName() + "\n" + e1.getId() + "\n" +
e1.getSalary() + "\n" + e1.getOffice() + "\n" + e1.getExtension() + "\n" +
e1.getYearsOfServ() + "\n" + "\n");
tv.append("Employee 2:\n" + e2.getName() + "\n" + e2.getId() + "\n" +
e2.getSalary() + "\n" + e2.getOffice() + "\n" + e2.getExtension() +
"\n" + e2.getYearsOfServ() + "\n" + "\n");
tv.append("Employee 3:\n" + e3.getName() + "\n" + e3.getId() + "\n" +
e3.getSalary() + "\n" + e3.getOffice() + "\n" + e3.getExtension() +
"\n" + e3.getYearsOfServ() + "\n" + "\n");
tv.append("The average years of service:\n " +
((e1.getYearsOfServ() + e2.getYearsOfServ() + e3.getYearsOfServ()) / 3.0) + "\n");
fsc.close();
}
catch(IOException e)
{
tv.setText("Error: Invalid URL Address or File Does Not Exist");
}
該表達式:
(e1.getYearsOfServ() + e2.getYearsOfServ() + e3.getYearsOfServ()) / 3
是整數除法; 因此結果是一個int
。
而且String.format()
正確地抱怨它不能使用"%.2f"
來格式化int,因此是錯誤的。
您在這里需要一個雙精度數,因此您至少需要除法的一個操作數是一個雙精度數:
(e1.getYearsOfServ() + e2.getYearsOfServ() + e3.getYearsOfServ()) / 3.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.