1. 使用 JOptionPane 类的 showInputDialog()和 showMessageDialog()两个方法,实 现一个华氏温度和摄氏温度相互转换的程序。转换公式如下:F = (9/5)*C+32;
两个方法的使用方法如下:
文件命名和路径情况:
package com.design;
import javax.swing.*;
/**
* @Author lanxiaofang
* @email [email protected]
* @date 2020/09/07 08:30
*/
public class UseJOptionPane {
public static void main(String[] args) {
while (true){
String string = InputTemperature();
if ("exit".equals(string))
{
System.out.println("--程序终止--");
JOptionPane.showMessageDialog(null,"程序已终止,感谢您的使用", "温度转换结果", JOptionPane.INFORMATION_MESSAGE);
return; //return关键字并不是专门用于跳出循环的,return的功能是结束一个方法。 一旦在循环体内执行到一个return语句,return语句将会结束该方法,循环自然也随之结束。与continue和break不同的是,return直接结束整个方法,不管这个return处于多少层循环之内。
}
else
{
int string_length = string.length();
if (string_length > 1)
{
String stringTemperature = string.substring(0, string_length - 1); // 从第0位获取到倒数第二位
int temperature = 0;
try
{
temperature = Integer.parseInt(stringTemperature);
} catch (NumberFormatException numberFormatException)
{
System.out.println("NumberFormatException: " + numberFormatException);
} catch (NullPointerException nullPointerException)
{
System.out.println("NullPointerException : " + nullPointerException);
}
catch (Exception exception)
{
System.out.println("Exception : " + exception);
}
String type = string.substring(string_length - 1, string_length); //截取最后一个字符,来判断输入的温度格式
TemperatureConversion(type, temperature);
}
else
{
continue; //continue中止本次循环,接着开始下一次循环。
}
}
}
}
public static String InputTemperature()
{
String string = JOptionPane.showInputDialog(null, "摄氏度请输入#C,如5C,华氏温度请输入#F,如5F。终止程序请输入\"exit\",或点击取消按钮","温度相互转换",JOptionPane.QUESTION_MESSAGE);
System.out.println("输入的内容是" + string);
return string;
}
public static void TemperatureConversion(String type, int temperature)
{
if ("F".equals(type)){
System.out.println("输入的是华氏度,要转换成摄氏度C");
int C = (temperature-32)*5/9;
JOptionPane.showMessageDialog(null,"您输入的是"+temperature+"F,转换后的摄氏度是:"+C+"C","温度转换结果", JOptionPane.INFORMATION_MESSAGE);
}
else if("C".equals(type)){
System.out.println("输入的摄氏度,要转换成华氏摄氏度F");
int F = temperature*9/5+32;
JOptionPane.showMessageDialog(null,"您输入的是"+temperature+"C,转换后的华氏度是:"+F+"F","温度转换结果", JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null,"您输入的格式有误", "温度转换结果", JOptionPane.INFORMATION_MESSAGE);
}
}
}
运行结果如下: