Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Two Dimensional Array

 
Bobby Joseph
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50241
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic