转换类不适用于java

时间:2015-01-12 14:15:40

标签: java

我是转换课程的新手。我试图使用方法从一个变量转换为另一个变量。目前,我不确定如何将double转换为int然后将其舍入以及如何将boolean转换为int,以便0 = false1 = true。有人可以帮忙吗?

我的代码:

public class MethodsOverloading {

    public int convert (String s) {
        System.out.println("This is a string "+ s); // Hoping to display 100 as a string
        return 0;
    }

    public int convert(double d) {
        System.out.println("This is an int "+ d); // Want to display 99.6 rounded to 100 (so its an int)
        return 0;
    }

    public int convert (boolean b) {
        System.out.println("This is an int "+(b)); // hoping to return as an int with 0 = false and 1 = true
        return 0;
    }

    public static void main(String[] args) {
        MethodsOverloading overload = new MethodsOverloading();
        overload.convert("100");
        overload.convert(99.6);
        overload.convert(true);
    }
}

4 个答案:

答案 0 :(得分:1)

使用

System.out.println("This is an int "+ Math.round(d/100.0)*100); // Want to display 99.6 rounded to 100 (so its an int)

表示double方法,

System.out.println("This is an int "+(b?1:0)); // hoping to return as an int with 0 = false and 1 = true

用于int方法。

答案 1 :(得分:1)

布尔:

if ( trueExpression ){ return 1;}
else { return 0;}

在下一行中,你自相矛盾:

System.out.println("This is an int "+ d); // Want to display 99.6 rounded to 100 (

99.6不是int。 100是。所以,如果你想显示99.6,你需要

"this is a double: " + (double)d

通知jvm它是双重的,它应该可以工作。

答案 2 :(得分:0)

您可以使用此方法从String获取整数:

Integer.parseInt(s);

要从double获取整数,您可以使用ceil中的Math方法,并将其结果转换为整数:

(int) Math.ceil(d)

而且,要将boolean转换为整数,您可以使用这个简单的逻辑:

if (b) // this is equivalent to `if (b == true)`
    return 1;
else
    return 0;

请注意,建议使用if (b)代替if (b == true)

答案 3 :(得分:0)

你的意思是这样的:

public int convert (boolean b) {
  // conversion: 1 - true, 0 - false
  int result = b ? 1 : 0;

  // debug information printing out 
  System.out.println("This is an boolean " + result); 
  // Do you really want to return 0 in any case? 
  // Returning conversion result looks far better
  return result; 
}
相关问题