开发者

Java: Converting ints & doubles to floats?

Working on my assignment for Java and I have created a class called Triangle. This has 3 variables, side1, side2 and side3. My constructor method takes 3 float values and assigns them to each variable in turn.

My issue is if the user puts in (10,11.1,1开发者_StackOverflow社区2.2) those are taken as (int,double,double) and not the float that I require (the assignment says the 3 sides must be float values).

So how can I convert each input into a float regardless of if it's an integer or double when inputted?

Thanks,

Jack.


You will generally read the data in as the appropriate type -- e.g. Scanner.nextFloat. This will read "10" (or "11.1") as a float. To the compiler the only thing that matters is the type signatures.


Make your variable/parameters type Number. A number can be easily converted to any other numeric primitive type.

Number n1 = (int)1;
Number n2 = (double)123.456;

Float f1 = n1.floatValue();
Float f2 = n2.floatValue();


I'm assuming you're using literals which is causing the problem? Sticking an "f" after them will make them floats. Otherwise it's completely dependent on your user interface and how you're getting the values.


If you're accepting user input then you'll almost certainly be dealing with strings at the user level. If this is the case then you can use Float.valueOf(String) to get the float representation of a string.

You'll find the valueOf(String) static method on most, if not all, of the numeric types in Java for this kind of thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜