I need to convert the result of a calculation from type double to type int, what's the best way of going about this?
I need to do this because I need the results of the calculation to be the length of a rectangle that will be drawn.
Many thanks :)
Printable View
I need to convert the result of a calculation from type double to type int, what's the best way of going about this?
I need to do this because I need the results of the calculation to be the length of a rectangle that will be drawn.
Many thanks :)
You can cast it: int i = (int)1.3;
Ok I think I got that, but BlueJ is saying that I'm having an error still.
Code Java:import java.awt.*; import javax.swing.*; public class goldenrect extends JApplet { double length; public void init() { String shortSide; double shortnumb; shortSide = JOptionPane.showInputDialog ("Enter the length of the shorter side in pixels"); shortnumb = Integer.parseInt( shortSide ); length = shortnumb * 1.6180339887; int shortnumb2 = (int) shortnumb; int length2 = (int) length; } public void paint ( Graphics g ) { g.drawRect( 15, 10, length2, shortnumb2 ); g.drawString( "The length of the longer side is " + length, 25, 25); } }
It says that it cannot find the symbol- variable length2
Any ideas? Any help is greatly appreciated :)
What line is the error on?
Is length2 a local variable in a method?
or is it a class variable know to all methods?
Local variables are only known in the method (or enclosing {}s) they are defined in.
Yeah that's what the problem was, I hadn't declared length2 as a class variable, thanks :)
However now I have the problem that the conversion from double to int makes the int value 0, any ideas why this might be?
import java.awt.*;
import javax.swing.*;
public class goldenrect extends JApplet
{
double length, shortnumb;
int length2, shortnumb2;
String shortSide;
public void init()
{
String shortSide;
double shortnumb;
shortSide =
JOptionPane.showInputDialog ("Enter the length of the shorter side in pixels");
shortnumb = Double.parseDouble( shortSide );
length = shortnumb * 1.6180339887;
int shortnumb2 = (int) shortnumb;
int length2 = (int) length;
}
public void paint ( Graphics g )
{
g.drawRect( 15, 10, length2, shortnumb2 );
g.drawString( "The length of the longer side is " + length, 25, 25);
}
}
Never mind I've figured it out myself, I just had to move
int shortnumb2 = (int) shortnumb;
int length2 = (int) length;
into the public void paint class.
Thanks for all your help :)
you can parse.. or change data type into INT.. or cast