-2

我是 Java 新手,我一直在尝试做的事情:

tempTrailerArr是一个 String[] = {"12.0 1.1", "24.51", "34.12", "82.87 231.2 1.1 2.2"}

的每个元素tempTrailerArr都转换为一个 Scanner 对象trScan

tempTrailerArr 中每个元素的第一个 double 将存储在名为 的 Double[] 中trailerVals

所以期望的结果是tempTrailerArr= {12.0 24.51 34.12 82.87}

但是,下面的代码不会终止,我不明白为什么?

        for (int j=0; j<tempTrailerArr.length; j++) {
        Scanner trScan = new Scanner(tempTrailerArr[j]);
        switch (j) {
        case 0: 
        case 1: 
        case 2: 
        case 3: this.trailerVals[j] = trScan.nextDouble();
                break;
        }
    }
4

3 回答 3

0

而不是“在拆分后将值从 String 转换为 double ” - 您需要使用 Double.parseDouble(String s) 将字符串转换为 double (如果您使用其他方法。)

String [] tempTrailerArr =  {"12.0 1.1", "24.51", "34.12", "82.87 231.2 1.1 2.2"};

String [] tempTrailerVals = null;
double[] trailerVals = new double [tempTrailerArr.length];

for (int i = 0 ; i < tempTrailerArr.length ; i ++)
{
    tempTrailerVals = tempTrailerArr[i].split(" ");
    // you should also add some error handling here - what if we can't convert the value to a double?
    trailerVals[i] = Double.parseDouble(tempTrailerVals[0]);

}
于 2013-09-09T21:30:36.953 回答
0

解释你的代码:

// loop start :
for (int j=0; j<tempTrailerArr.length; j++) {

    // creating a new Scanner object every time this loop starts
    // this scanner starts scanning the String value received from this element in the array
    Scanner trScan = new Scanner(tempTrailerArr[j]);

    // checks for the numerical value of J :
    switch (j) {

    // if j == 0, nothing happens, and go for the next case (no break mentioned)
    case 0: 

    // if j == 1, nothing happens, and go for the next case (no break mentioned)
    case 1: 

    // if j == 2, nothing happens, and go for the next case (no break mentioned)
    case 2: 

    // if j == 3 (and this will be true in case 0, case 1, case 2) 
    // trailerVals[j] = next double (if no double was found, an "InputMismatchException will be thrown
    // to use nextDouble(), first you should check if trScan.hasNextDouble(),
    // if true, then add double, else do nothing
    case 3: this.trailerVals[j] = trScan.nextDouble();

    // every time j will be less than or equal to 3, it will reach this point
       break;
    }
}

我解释了您的代码,因为这是您的问题,但是如果您想将 String 数组分成几部分,请使用 String.split() 方法,或使用 (for:each) 循环并检查值并将其添加到所需的大批

请不要尝试继续执行此代码,这是徒劳的

于 2013-09-09T21:35:28.740 回答
0

您可以做的是使用拆分功能并拆分“”(空格)上的字符串。

因此,您不需要扫描器,只需在拆分后将值从 String 转换为 double 即可。

于 2013-09-09T21:20:57.220 回答