如何在Java中将字符串转换为数值。

huangapple go评论135阅读模式
英文:

How to convert String to numerical value in Java

问题

我正在进行神经网络项目的工作,在数据集中我只有字符串值,但我知道神经网络只接受数字值,所以我该如何将字符串转换为类似于以下的双精度数值:

“red” = 0.4582932
“green” = 0.512932
“black” = 0.542123
英文:

I'm working on my Neural Network project, and in data set I have only string values, but I know that NN accepts only numerical values so how can I convert string to double like this :

“red” =   0.4582932
“green” = 0.512932
“black” = 0.542123

答案1

得分: 1

如果值是动态的,那么可以使用@ElliotFrisch在问题评论中提供的解决方案,该解决方案涉及使用分别为String和Double类型的Map。

如果值是预定的且不会更改,那么枚举可能是您的解决方案。

enum Color {
    RED(0.4582932),
    GREEN(0.512932),
    BLACK(0.542123);

    private final double value;

    private Color(double value) {
        this.value = value;
    }
}

然后,您可以创建一个枚举值的集合。在此使用ImmutableSet

private static final Set<Color> COLORS = ImmutableSet.copyOf(EnumSet.allOf(Color.class));
英文:

If the values are dynamic then use the solution that @ElliotFrisch provided in the question comments regarding the use of a Map of type String and Double respectively.

If the values are predetermined and do not change then an enumeration might be the solution for you.

enum Color {
    RED(0.4582932),
    GREEN(0.512932),
    BLACK(0.542123);

    private final double value;

    private Color(double value) {
        this.value = value;
    }
}

You could then create a Set of the enum values. ImmutableSet here.

private static final Set&lt;Color&gt; COLORS = ImmutableSet.copyOf(EnumSet.allOf(Color.class));

huangapple
  • 本文由 发表于 2020年5月19日 21:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/61892069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定