gpt4 book ai didi

java - 数组列表。 ArrayList 到 int 和 double

转载 作者:行者123 更新时间:2023-11-29 05:28:37 25 4
gpt4 key购买 nike

我遇到的问题是我无法从 arraylist 中取出一个数字并将其变成我拥有的 intdouble使用体重和高度来计算 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() 或解析方法。有关详细信息,请参阅 WOUNDEDEStevenJones 的回答。

关于java - 数组列表。 ArrayList 到 int 和 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21886196/

25 4 0