扫描仪给出相同的值2x而不是1

时间:2012-11-03 16:14:37

标签: java variables input scope

所以我有这个功能:

当我使用下面的代码时,我将球体半径传递给扫描仪,他确定了 double并且应该将它们传递给toRound函数。

    String outputDoubles = " double one: 190.234567 and double two: 370.03245 "; 

    Scanner doubles = new Scanner(outputDoubles);
    doubles.useDelimiter("[^\\p{Alnum},\\.-]");
    while(true) {
        double takeDouble;

        if (doubles.hasNextDouble()) {
            takeDouble = doubles.nextDouble(); // takedouble
            System.out.println(toRound(takeDouble));

        }

        if (doubles.hasNext()) {
            doubles.next();


        }
        else {
            break;
        }

    } 

toRound如下:

static String toRound (double number) {
    double x = number; // nog fixen
    System.out.println(" \n");
    double y = number; 
    return "" + x + y;
}    

问题是它不返回:190.234567但它返回:190.234567190.234567190 所以它会在彼此之后返回2次。

有没有办法解决这个问题,我几个小时都在尝试不同的事情,但是无法让它发挥作用。

1 个答案:

答案 0 :(得分:4)

return "" + x + y;会将'x'转换为String然后追加它,将'y'转换为String然后追加,从而加倍输出。

您需要重写此表达式"" + (x + y),以便在将表达式转换为String之前对其进行求值。