一,四则运算
(一) 设计思想
使用Scanner类读取运行时用户输入数据,然后进行数据类型转换,完成四则运算之后利用输出类输出。
(二) 流程图
(三)程序代码
//Zhangxiaochen 2015/10 04 四则运算
import javax.swing.JOptionPane; // import class JOptionPane
public class Operation {
public static void main( String args[] )
{
String firstNumber, // first string entered by user
secondNumber; // second string entered by user
int number1, // first number to add
number2, // second number to add
sum, // sum of number1 and number2
redu, //reduction of number1 and number2
pro; //product of number1 and number2
float div; //divistor of number1 and number2
// read in first number from user as a string
firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a string
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert numbers from type String to type int
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add the numbers
sum = number1 + number2;
redu=number1 - number2;
pro=number1 * number2;
div=number1 /number2;
// display the results
JOptionPane.showMessageDialog(
null,
"和是:" + sum+"\n"+
"差是:" + redu+"\n"+
"积是:" + pro+"\n"+
"商是:" + div+"\n",
"Results",
JOptionPane.PLAIN_MESSAGE );
System.exit( 0 ); // terminate the program
}
}
(四)运行截图
二EnumTest
(一) 程序代码
public class EnumTest {
public static void main(String[] args) {
Size s=Size.SMALL;
Size t=Size.LARGE;
//s和t引用同一个对象?
System.out.println(s==t); //
//是原始数据类型吗?
System.out.println(s.getClass().isPrimitive());
//从字符串中转换
Size u=Size.valueOf("SMALL");
System.out.println(s==u); //true
//列出它的所有值
for(Size value:Size.values()){
System.out.println(value);
}
}
}
enum Size{SMALL,MEDIUM,LARGE};
(二) 运行截图
(三) 思考
枚举类型不能直接运算,需要进行类型转换才能比较大小或运算。
三TestDouble
(一) 程序代码
public class TestDouble {
public static void main(String args[]) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
}
}
(二)运行截图
(三)思考
double类型由于精度问题会产生数据精度损失