2

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,12.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.

mskfisher
3,4124 gold badges38 silver badges50 bronze badges
asked Dec 7, 2010 at 23:40
2
  • 4
    How are you getting the input? Commented Dec 7, 2010 at 23:41
  • At this stage I'm not getting input from the user, I have to manually enter it, and my assignment states the three values entered must be 10,11.1 and 12.2). Commented Dec 9, 2010 at 0:20

4 Answers 4

3

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.

answered Dec 7, 2010 at 23:45
Sign up to request clarification or add additional context in comments.

Comments

2

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();
answered Dec 8, 2010 at 0:22

Comments

1

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.

answered Dec 7, 2010 at 23:48

Comments

1

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.

answered Apr 14, 2011 at 21:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.