[英]ArrayList. ArrayList to int and double
我有一個問題,我不能從arraylist
取一個數字並將其變成一個int
或double
,我必須做的是使用重量和高度來計算BMI。 請看一看!
分配是將客人的體重,長度和姓名放入其中,並對那些長度與身高比例較差的人進行排序。 在主要的我創建一個包含幾個客人的數組,當我運行它時說:
"Exception in thread "main" java.lang.NumberFormatException: For input string "name"
和
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Diet.putOnDiet(Diet.java:12)
at TestDiet.main(TestDiet.java:7)
Diet
班如下:
public class Diet{
public static ArrayList<Guest> putOnDiet(ArrayList <Guest> list){
ArrayList<Guest> namn = new ArrayList<Guest>();
ArrayList<Guest> hej = new ArrayList<Guest>();
for(int i = 0; i<=list.size()/3; i = i+3){
int langd = Integer.parseInt(list.get(i+1).toString()); //I dont know how to make this work
double vikt = Double.parseDouble(list.get(i).toString());
String name = list.get(i+2).toString();
if ((vikt) > 1.08*(0.9*(langd -100))){
namn.add(new Guest(vikt, langd, name));
}
}
return namn;
}
}
Guest
班:
public class Guest {
private double weight; private double length; private String name;
public Guest(double weight, double length, String name){
this.name = name; this.weight = weight; this.length = length; // Maybe the problem is here. How do you modify the class to make it work?
}
public String getName() {
return name;
}
public double getWeight()
{
return weight;
}
public double getLength() {
return length;
}
public void setName(String name) {
this.name = name;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setLength(double length)
{ this.length = length;
}
public boolean isSlim() {
if (weight >= 1.08 * 0.9 * (length - 100)) {
return false;
}
else
return true;
}
public String toString() {
return name + "\n" + weight + "\n" + length;
}
}
你確定要解析一個整數嗎?
當無法解析數字時,拋出井號解析異常。 當字符串不是“somthing#$%^&”之類的數字時。 所以嘗試更換這一行
int langd = Integer.parseInt(list.get(i+1).toString());
有了這個
try {
int langd = Integer.parseInt(list.get(i+1).toString());
} catch (NumberFormatException e) {
System.out.println(list.get(i+1).toString() +" : This is not a number");
System.out.println(e.getMessage());
}
編輯閱讀WOUNDEDStevenJones后,我也認為你不應該使用toString()或解析方法。 有關詳細信息,請參閱WOUNDEDStevenJones答案。
看起來你想要改成它
for (int i=0; i<list.size(); i++) {
double langd = list.get(i).getLength();
double vikt = list.get(i).getWeight();
String name = list.get(i).getName();
}
並為此目的忽略你的getString()
方法
注意:我不確定你要對不同的索引做什么,但它們可能都是.get(i)
方法list.get(i)將返回Guest
類型的對象。 Guest
有方法, getWeight()
和getLength()
。
list.get(i).getWeight()
這實際上會給你一個雙倍的回報。 和,
Integer.parseInt(list.get(i).getWeight().toString())
這應該能夠解析。
希望這可以幫助。
_san
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.