J ava Problrm: Part1: Implement the CelsiusConverter program Part II: Enhance yo
ID: 660947 • Letter: J
Question
Java Problrm:
Part1:
Implement the CelsiusConverter program
Part II:
Enhance your program so that can it can also convert Fahrenheit to Celsius.
You should call this version the TemperatureConverter program.
Here is CelsiusConverter program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CelsiusConverter implements ActionListener {
JFrame frame;
JPanel panel;
JTextField tempCelsius;
JLabel cLabel, fLabel;
JButton convertTemp;
public static void main(String[] args) {
CelsiusConverter converter = new CelsiusConverter();
}
// Constructor
public CelsiusConverter() {
// Create the frame and container.
frame = new JFrame("Convert Celsius to Fahrenheit");
panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
addWidgets();
// Add the panel to the frame.
frame.getContentPane().add(panel);
// Exit when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Show the converter.
frame.pack();
frame.setVisible(true);
}
// Create and add the widgets for converter.
private void addWidgets() {
// Create widgets.
tempCelsius = new JTextField();
cLabel = new JLabel("Celsius");
convertTemp = new JButton("Convert...");
fLabel = new JLabel("Fahrenheit");
// Listen to events from Convert button.
convertTemp.addActionListener(this);
// Add widgets to container.
panel.add(tempCelsius);
panel.add(cLabel);
panel.add(convertTemp);
panel.add(fLabel);
// Implementation of ActionListener interface.
public void actionPerformed(ActionEvent event)
{
// Convert Celsius to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32);
fLabel.setText(tempFahr + " Fahrenheit");
}
}
Explanation / Answer
The explanation for my answer given above:
It is a temperature conversion program that asks the user to choose between Celsius-to-Fahrenheit conversion or Fahrenheit-to-Celsius conversion. The user will also have the option to quit the program. (You can use 1, 2, and 3 respectively).
- If the incorrect choice is typed, display an error message and prompt the user to re-enter his/her choice.
- Once the user has chosen which type of conversion he/she wants, the program should prompt the user to enter the temperature value to convert. Finally, display the converted value.
- Depending on the choice, use the following formulas accordingly:
Formula to convert from Celsius to Fahrenheit: ((9/5)*degC)+32.
Formula to convert from Fahrenheit to Celsius: 5*(degF-32)/9
- The process must continue until the user enters the option to quit the program.
- You must create two separate functions for the temperature conversion: one for the Celsius-to-Fahrenheit conversion and another one for the Fahrenheit-to-Celsius conversion.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.