Solved

Java programming declaring and assigning a value to a float variable

Posted on 2014-01-25
1
390 Views
Last Modified: 2014-01-25
I'm using Eclipse and Java.

I am trying to declare and assign a value to a float variable.
Below are the 2 examples I have. On both examples its not liking how I'm assigning the value to the variable

How do I fix both of these examples?


Example 1:

public class TestClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		float x;
							
		x = 2.14239;

		
		System.out.println("The value is: " + x );


	}

}

Open in new window


Example 2:

public class TestClass {

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            float y;
                                          
            y = 6.02E23;

            
            System.out.println("The value is: " + y );


      }

}
0
Comment
Question by:maqskywalker
1 Comment
 
LVL 26

Accepted Solution

by:
dpearson earned 500 total points
ID: 39809570
There are 2 floating point types you can use in Java: "float" and "double".

99.99999% of the time you should double (it's more accurate - float is just a historical type that has little use today).  Also by default a constant like "1.23" is type "double" instead of type "float" - which is the error you're getting here.

So if you switch to:

double x ;
x = 2.14239;

and

double y ;
y = 6.02E23;

All should be well.

Doug
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question