为什么双精度不能从我的String []数组正确解析? [英] Why do doubles not correctly parse from my String[] array?

查看:155
本文介绍了为什么双精度不能从我的String []数组正确解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从单个维String数组解析双精度值.当我尝试执行此操作时,双精度值始终解析为0.0,而不是正确的值.为什么会这样?

I am trying to parse double values from a single dimension String array. When I attempt to do this, the doubles always parse as 0.0, never as the correct value. Why is this the case?

代码:

解析器方法:(忽略整数解析器,当给定整数时此解析器工作正常)

Parser Method: (Ignore integer parser, this one works fine when given an integer)

NumReturn numberParser(int cIndex) { // current index of array where num is
        NumReturn nri;
        NumReturn nrd;
        try {
        nri = new NumReturn(Integer.parseInt(Lexer.token[cIndex]), cIndex++, 'i');
        System.out.println(nri.value + " ");
        return nri;
        }
        catch (NumberFormatException intExcep) {

          }
        try {
        nrd = new NumReturn(Double.parseDouble((Lexer.token[cIndex])), cIndex++, 'd');
        System.out.println(nrd.dvalue + " ");
        return nrd;
        }
        catch (NumberFormatException doubExcep) {
            doubExcep.printStackTrace();
          }
        return null;


    }

NumReturn类:

package jsmash;

public class NumReturn {
    int value;
    double dvalue;
    int pointerLocation;
    char type;
    NumReturn(int value, int pointerLocation, char type) {
        this.value = value;
        this.pointerLocation = pointerLocation;
        this.type = type;
    }
    NumReturn(double dvalue, int pointerLocation, char type) {
        this.dvalue = value;
        this.pointerLocation = pointerLocation;
        this.type = type;
    }
}

我要从中解析的字符串数组:

static String[] token = new String[100];
token[0] = "129.4"; // I call my parser on this element of the array
token[1] = "+";
token[2] = "332.78"; // I call my parser on this element of the array

推荐答案

在我看来,这里的问题是一个简单的错字.在第二个NumReturn构造函数(具有double参数的构造函数)中,当前具有以下内容:

It looks to me like the problem here is a simple typo. In the second NumReturn constructor (the one with the double parameter), you currently have the following:

this.dvalue = value;

这会将this.dvalue赋给this.value的初始值为0.它完全忽略了构造函数参数.您真正想要的是这样:

This will assign this.dvalue to the initial value of this.value, which is 0. It is ignoring the constructor parameter entirely. What you actually want is this:

this.dvalue = dvalue;
              ^

这篇关于为什么双精度不能从我的String []数组正确解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆