*
The moose likes Beginning Java and the fly likes Two Dimensional Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Two Dimensional Array" Watch "Two Dimensional Array" New topic
Author

Two Dimensional Array

Bobby Joseph
Greenhorn

Joined: May 29, 2010
Posts: 1


This program generates the following errors..

found : double
required: float
float twoD[][] = { {9*3.2 , 5.2-2 , 7*5},{9*6 , 6-2 , 8*5},{32*6 , 0-2 , 8*5}};
possible loss of precision

Can any one explain the error. I changed the float to double and the error vanishes.

This is the output generated

28.8 3.2 35.0
54.0 4.0 40.0
192.0 -2.0 40.0

But all these are float values. I know it is something related with type casting but can someone tell me exactly what is going wrong.
Sujeet Kumar Jaiswal
Greenhorn

Joined: Mar 07, 2010
Posts: 17
Actually, by default a decimal number is double in java. Hence, 9*3.2 & 5.2-2 will result in a double number which cannot be directly casted to float. Try

float twoD[][] = { {9*3.2f , 5.2f-2 , 7*5},{9*6 , 6-2 , 8*5},{32*6 , 0-2 , 8*5}};

This will work as suffixing 'f' with a decimal number makes it float.

Hence,

float f = 3.2 (compiler error)
float f = 3.2f (compiler happy)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38075
    
  22
Welcome to the Ranch

I shall add code tags to your post, so you can see how much easier it is to read (if it is indented).

I shall also go all pedantic and remind you there is no such thing as a 2D array. Java™ only supports arrays; what you have as a float[][] is an array of arrays.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Two Dimensional Array
 
Similar Threads
struct in java
[solved]warning message:" Accessing static method numbers" #7th floor
Question on switch
Something i'm extremely confused on
how to use array in array?