Why do doubles not correctly parse from my String[] array?

本小妞迷上赌 提交于 2019-12-10 23:57:16

问题


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?

Code:

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 Class:

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;
    }
}

String array which I am trying to parse from:

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

回答1:


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 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;
              ^


来源:https://stackoverflow.com/questions/34536498/why-do-doubles-not-correctly-parse-from-my-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!