[实验目的]
1、熟悉和掌握在Eclipse环境下编译运行Java文件,熟悉JOptionPane的各种对话框的使用;熟悉Java的各种运算符的使用。
[实验内容和步骤]
1、 让用户输入三个对话框,前两个对话框输入操作数,第三个对话框输入运算符。运算符包括:加、减、乘、除、取模、自增(++)、自减(–)和字符串相加(+);
2、 第四个对话框让用户选择是否继续。若点击“Yes”按钮,则重复执行第1步,若点击“No”按钮,则退出程序。
自增(++)例子:
firstNumber = 2; secondNumber=3; operator=++;
结果:results= “firstNumber=4,secondNumber=4”
字符串相加(+)例子,当输入非数字的字符串时,
firstNumber = “hello”; secondNumber=“world”; operator=+;
结果:results= “hello world”;
下面是当用户输入两个整数和相加的运算符得到的结果:
import javax.swing.*;
public class hello {
public static void main(String[] args){
int x=0;
String firstin, secondin, op;
int a, b, ret, ret1, ret2;
while(x==0) {
int flag = 0; //用来标记输入的是否为整数
/*输入提示框 1:输入第一个操作数*/
firstin = JOptionPane.showInputDialog(null, "Enter first operand:");
/*输入提示框 2:输入第二个操作数*/
secondin = JOptionPane.showInputDialog(null, "Enter second operand:");
/*输入提示框 3:输入操作符*/
op = JOptionPane.showInputDialog(null, "Enter operator:");
//默认同时输入字符串或整数
/*判断输入的是字符串还是整数*/
for (int i = 0; i < firstin.length(); i++) {
if (firstin.charAt(i) > '0' && firstin.charAt(i) < '9') {
//输入的是整数
flag = 1;
} else {
//输入的是字符串
flag = 0;
break;
}
}
if (flag == 1) {
a = Integer.parseInt(firstin);
b = Integer.parseInt(secondin);
if ("+".equals(op)) {
ret = a + b;
JOptionPane.showMessageDialog(null, "result=" + ret);
} else if ("=".equals(op)) {
ret = a - b;
JOptionPane.showMessageDialog(null, "result=" + ret);
} else if ("*".equals(op)) {
ret = a * b;
JOptionPane.showMessageDialog(null, "result=" + ret);
} else if ("/".equals(op)) {
ret = a / b;
JOptionPane.showMessageDialog(null, "result=" + ret);
} else if ("%".equals(op)) {
ret = a % b;
JOptionPane.showMessageDialog(null, "result=" + ret);
} else if ("++".equals(op)) {
ret1 = a + 1;
ret2 = b + 1;
JOptionPane.showMessageDialog(null, "firstnum=" + ret1 + "secondnum=" + ret2);
} else if ("--".equals(op)) {
ret1 = a - 1;
ret2 = b - 1;
JOptionPane.showMessageDialog(null, "firstnum=" + ret1 + ",secondnum=" + ret2);
}
} else {
if ("+".equals(op)) {
JOptionPane.showMessageDialog(null, firstin + ' ' + secondin);
}
}
/*选择提示框 4:选择是否继续*/
Object[] choose = {"Yes", "No"};
x = JOptionPane.showOptionDialog(null, "是否继续?", "标题", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, choose, choose[0]);
}
}
}