java only Write a Java program that converts miles and kilometer, as shown in Fi
ID: 3717036 • Letter: J
Question
java only
Write a Java program that converts miles and kilometer, as shown in Figures 17.37. If you enter values in the Mile text field, the Kilometer text field is focused (or the cursor is blinking in the Kilometer text field), and press the ENTER key, the corresponding kilometer is displayed in the Kilometer text filed. Likewise, If you enter values in the Kilometer text field, the Mile text field is focused (or the cursor is blinking in the Mile text field), and press the ENTER key, the corresponding mile is displayed in the Mile text filed. Two sample runs of the program are shown as follows.
Explanation / Answer
Note : create java project and package in that and create class DistanceConverter
First clear the input boxes before tying for conversion.....this the main thing that you need to do....
///////////////////////conversion using applets/////////////
import java.applet.Applet;
import java.awt.Button;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DistanceConverter extends Applet implements ActionListener
{
private static final double MILES_PER_KILOMETER = 0.621;
private static final double KILOMETER_PER_MILES = 1.609;
Label l1= new Label("KMS");
Label l2= new Label("MILES");
TextField t1 = new TextField(10);
TextField t2 = new TextField(10);
Button enter = new Button("ENTER");
public void init()
{
add(l1);
add(t1);
add(l2);
add(t2);
add(enter);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == enter)
{
double n1=0,n2=0;
if(!t1.getText().isEmpty())
n1 = Double.parseDouble(t1.getText());
if(!t2.getText().isEmpty())
n2 = Double.parseDouble(t2.getText());
if( n1>0){
double mi = n1 * MILES_PER_KILOMETER;
String miles = String.valueOf(mi);
t2.setText(miles);
}
else if(n2>0){
double mi = n2 * KILOMETER_PER_MILES;
String miles = String.valueOf(mi);
t1.setText(miles);
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.