gpt4 book ai didi

java - 不兼容的类型;字符串无法转换为 double : JAVA TOKEN

转载 作者:行者123 更新时间:2023-12-01 06:50:43 24 4
gpt4 key购买 nike

[编辑]澄清这是一个不同的问题:我的问题是关于将字符串解析为双倍以使 token 接受它,并且没有此问题的答案 Java Double to String conversion without formatting符合我的标准。

我有一个以下格式的文件:

A B 10
A C 12
A D 8
B D 5
B E 2
...

以下是将上述数据存储到arraylist中的代码。但它只存储起始节点、结束节点,不存储成本。

List<Node1> list = new ArrayList<Node1>();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node1(tokens[0], tokens[1], tokens[2])); // Error at tokens[2]
}

以下是我的 Node1 类

class Node1 {
String start, end;
double cost;

public Node1(String start, String end, double cost){
this.start = start;
this.end = end;
this.cost = cost;
}

public String getStartNode() {
return start;
}

public String getEndNode(){
return end;
}

public double getCost(){
return cost;
}
}

它在tokens[2]处给了我一个错误,如下

 Incompatible types; String cannot be converted to double 

我理解这个错误, token 期待字符串,但它发现了双重(成本),但我不知道如何解决这个问题。 token 不兼容读取双倍还是什么?如果没有,我应该使用什么来代替 tokens[2] 来存储我的 double 值?
我尝试过谷歌搜索,但似乎找不到任何解决方案。抱歉,我对这些东西很陌生。请多多包涵!

最佳答案

您需要将构造函数中的最后一个参数更改为 double 型。

list.add(new Node1(tokens[0], tokens[1], Double.parseDouble(tokens[2])));

您还可以重写构造函数。

public Node1(String start, String end, String cost) {
this(start, end, Double.parseDouble(cost));
}

关于java - 不兼容的类型;字符串无法转换为 double : JAVA TOKEN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30219246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com