数独计算器源码(java语言)
- 格式:doc
- 大小:44.00 KB
- 文档页数:9
计算器Java编程代码1、界面截图1、程序代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Counter implements ActionListener {// 改进小数问题private boolean append = false;JButton[] jb = new JButton[20];JTextField jtf = new JTextField(19);String[] st = { "Backs", "CE", "C", "+", " 7 ", " 8 ", " 9", "-"," 4 ", " 5 ", " 6", "*", " 1 ", " 2 ", " 3", "/"," . ", "+/-", " 0", "=", };String num1 = "0";String operator = "+";public Counter() {JFrame jf = new JFrame("计算器");// 界面设置GridLayout gl = new GridLayout(6, 1);jf.setLayout(gl);JPanel jp0 = new JPanel();jp0.add(jtf);jf.add(jp0);JPanel jp1 = new JPanel();for (int i = 0; i < 4; i++) {jb[i] = new JButton(st[i]);jp1.add(jb[i]);}jf.add(jp1);JPanel jp2 = new JPanel();for (int i = 4; i < 8; i++) {jb[i] = new JButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPanel jp3 = new JPanel();for (int i = 8; i < 12; i++) {jb[i] = new JButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPanel jp4 = new JPanel();for (int i = 12; i < 16; i++) { jb[i] = new JButton(st[i]);jp4.add(jb[i]);}jf.add(jp4);JPanel jp5 = new JPanel();for (int i = 16; i < 20; i++) { jb[i] = new JButton(st[i]);jp5.add(jb[i]);}jf.add(jp5);jtf.setEditable(false);// 文本框不可编辑jf.setResizable(false);// 窗口不可编辑jf.pack();// 自动调整窗口的大小// jf.setSize(240, 220);jf.setLocation(450, 300);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for (int i = 0; i < 20; i++) {// 注册监听jb[i].addActionListener(this);}}public void actionPerformed(ActionEvent ae) {String s = ae.getActionCommand();if (s.trim().matches("^\\d$")) {// 判断是输入的是否是数字if (append) {// 追加数字String ss = jtf.getText().trim();jtf.setText(ss + s.trim());} else {// 替换文本框原来的数字jtf.setText(s.trim());append = true;}} else if ("+-/*".indexOf(s.trim()) != -1) {// 判断按的是否是四则运算符num1 = jtf.getText();// 将第一次输入的数存储起来operator = s.trim();// 将输入的符号存储起来append = false;} else if ("=".equals(s.trim())) {String num2 = jtf.getText();double d1 = Double.parseDouble(num1);double d2 = Double.parseDouble(num2);if ("+".equals(operator)) {// 加法运算d1 = d1 + d2;} else if ("-".equals(operator)) {// 减法运算d1 = d1 - d2;} else if ("*".equals(operator)) {// 乘法运算d1 = d1 * d2;} else if ("/".equals(operator)) {// 除法运算d1 = d1 / d2;}jtf.setText(d1 + "");// 显示结果append = false;} else if (".".equals(s.trim())) {// 判断小数点String temp = jtf.getText();if (temp.indexOf(".") == -1) {jtf.setText(temp + ".");append = true;}} else if ("+/-".equals(s.trim())) {// 判断+/-String temp = jtf.getText();if(temp.startsWith("-")) {// 如果该数是负数则取负号后的数字jtf.setText(temp.substring(1));} else {// 如果是正数则在这个数前加上负号jtf.setText("-" + temp);}} else if ("CE".equals(s.trim()) || "C".equals(s.trim())) {// 判断复位键jtf.setText("0");append = false;} else if ("BackS".equals(s.trim())) {// 判断BackS键(删除)String temp = jtf.getText();if (temp.length() > 0) {jtf.setText(temp.substring(0, temp.length() - 1));}}}public static void main(String[] args) {new Counter();}}。
java计算器源代码(仿win)java计算器源代码(仿win7)import java.awt.*。
import javax.swing.*。
import java.awt.event.*。
class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar。
JMenu menu_check,menu_edit,menu_help。
JMenuItemmenuitem_science,menuitem_check,menuitem_exit,men uitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about。
JCheckBoxMenuItem menuitem_standard。
JTextField ta1。
int x,result2。
double op1,op2,opall。
private boolean end=false,flag=false,add=false,sub=false,cheng=fa lse,chu=false,flagop2=false。
JButtonb_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj ,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6 ,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_ dengyu。
JPanelp_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5。
private String str,resultstr。
//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"))。
JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。
//把代码改成Calc.java编译运行,完整版计算器,最下面是计算器界面import java.awt.*;import java.awt.event.*;public class Calc extends WindowAdapter implements ActionListener, MouseListener{Color cMoveOut=new Color(240 ,240 ,240);Color cMoveIn =new Color( 255,255,55);//状态变量boolean clicked=true;//判断是否单击了小数点boolean clear=true;//判断是否单击了符号位double previous;//记录第一个操作数double next;//记录第二个操作数String fuhao;//记录符号位int first=1;//标记是否开始一次新的运算过程Frame f;Panel p1,p2;TextField tf;Font fnt;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative,bBack;Button bPingFang , bDaoShu , bSin, bCos ,bTan;Button bC;GridLayout p2Layout;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);p1=new Panel(new FlowLayout());tf=new TextField(35);tf.setText("0.");tf.setEditable(false);p1.add(tf);f.add(p1,BorderLayout.NORTH);p2Layout=new GridLayout(5,5,5,4);p2=new Panel(p2Layout);f.add(p2,BorderLayout.CENTER);fnt=new Font("Serief",Font.BOLD,20);b1=new Button("1");b1.setFont(fnt);b2=new Button("2");b2.setFont(fnt);b3=new Button("3");b3.setFont(fnt);b4=new Button("4");b4.setFont(fnt);b5=new Button("5");b5.setFont(fnt);b6=new Button("6");b6.setFont(fnt);b7=new Button("7");b7.setFont(fnt);b8=new Button("8");b8.setFont(fnt);b7.setFont(fnt);b9=new Button("9");b9.setFont(fnt);b0=new Button("0");b0.setFont(fnt);b9.setFont(fnt);bPingFang=new Button("^2"); bPingFang.setFont(fnt); bDaoShu=new Button("1/X"); bDaoShu.setFont(fnt);bSin=new Button("sin");bSin.setFont(fnt);bCos=new Button("cos"); bCos.setFont(fnt);bTan=new Button("tan"); bTan.setFont(fnt);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this); bBack=new Button("Back");//退格bBack.setFont(fnt);bC=new Button("C");//清空bC.setFont(fnt);bDiv=new Button("/");bDiv.setFont(fnt);bSqrt=new Button("sqrt"); bSqrt.setFont(fnt);bMulti=new Button("*"); bMulti.setFont(fnt);bMinus=new Button("-"); bMinus.setFont(fnt);bPercent=new Button("%"); bPercent.setFont(fnt);bPlus=new Button("+"); bPlus.setFont(fnt);bEqual=new Button("="); bEqual.setFont(fnt);bDot=new Button(".");bDot.setFont(fnt);bNegative=new Button("+/-"); bNegative.setFont(fnt); bBack.addActionListener(this);bC.addActionListener(this); bDiv.addActionListener(this); bSqrt.addActionListener(this); bPingFang.addActionListener(this); bPercent.addActionListener(this); bDaoShu.addActionListener(this); bMulti.addActionListener(this); bPlus.addActionListener(this); bMinus.addActionListener(this); bMulti.addActionListener(this); bDiv.addActionListener(this); bSin.addActionListener(this); bCos.addActionListener(this); bTan.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this); bSqrt.addMouseListener(this); bPingFang.addMouseListener(this); bPercent.addMouseListener(this); bC.addMouseListener(this); bBack.addMouseListener(this);b7.addMouseListener(this);b8.addMouseListener(this);b9.addMouseListener(this); bDiv.addMouseListener(this); bDaoShu.addMouseListener(this); b4.addMouseListener(this);b5.addMouseListener(this);b6.addMouseListener(this); bMulti.addMouseListener(this); bSin.addMouseListener(this);b1.addMouseListener(this);b2.addMouseListener(this);b3.addMouseListener(this); bMinus.addMouseListener(this); bCos.addMouseListener(this);b0.addMouseListener(this); bDot.addMouseListener(this); bEqual.addMouseListener(this); bPlus.addMouseListener(this); bTan.addMouseListener(this);p2.add(bSqrt);p2.add(bPingFang);p2.add(bPercent);p2.add(bC);p2.add(bBack);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bDaoShu);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bSin);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bCos);p2.add(b0);p2.add(bDot);p2.add(bEqual);p2.add(bPlus);p2.add(bTan);f.setV isible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e) {if (first ==1)tf.setText("");first=0;Object temp=e.getSource();//退格if (temp== bBack){String s=tf.getText();tf.setText("");for (int i=0;i<s.length()-1;i++){char a=s.charAt(i);tf.setText(tf.getText()+a);}}//清零if (temp==bC){tf.setText("0.");clear=true;first=1;}if (temp==b0){//判断是否单击了符号位if (clear==false)tf.setText("");tf.setText(tf.getText()+"0");}if (temp==b1){if (clear==false)tf.setText("");tf.setText(tf.getText()+"1");clear=true;}if (temp==b2){if (clear==false)tf.setText("");tf.setText(tf.getText()+"2");clear=true;}if (temp==b3){if (clear==false)tf.setText("");tf.setText(tf.getText()+"3");clear=true;}if (temp==b4){if (clear==false)tf.setText("");tf.setText(tf.getText()+"4");clear=true;}if (temp==b5){if (clear==false)tf.setText("");tf.setText(tf.getText()+"5");clear=true;}if (temp==b6){if (clear==false)tf.setText("");tf.setText(tf.getText()+"6");clear=true;}if (temp==b7){if (clear==false)tf.setText("");tf.setText(tf.getText()+"7");clear=true;}if (temp==b8){if (clear==false)tf.setText("");tf.setText(tf.getText()+"8");clear=true;}if (temp==b9){if (clear==false)tf.setText("");tf.setText(tf.getText()+"9");clear=true;}//判断是否含有小数点if (temp == bDot){clicked=true;for (int i=0;i<tf.getText().length();i++)if ('.'==tf.getText().charAt(i)){clicked = false;break;}if (clicked == true){tf.setText(tf.getText()+".");clear=true;}}//bSqrtif(temp == bSqrt){tf.setText( Math.sqrt( Double.parseDouble(tf.getText())) + "" );clear=false;}//bPingFangif(temp == bPingFang ){tf.setText( Math.pow( Double.parseDouble(tf.getText() ), 2 ) + "" );clear=false;}//倒数if(temp == bDaoShu){tf.setText( 1 / Double.parseDouble(tf.getText()) + "" );clear =false;}//Sinif(temp == bSin){tf.setText( Math.sin( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//Cosif(temp == bCos){tf.setText( Math.cos( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//tanif(temp == bTan){tf.setText( Math.tan( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "");clear =false;}//加法运算if (temp==bPlus){previous=Double.parseDouble(tf.getText());fuhao="+";clear=false;//System.out.print("+");}//减法运算if (temp == bMinus){previous=Double.parseDouble(tf.getText());fuhao="-";clear=false;}//乘法运算if (temp == bMulti){previous=Double.parseDouble(tf.getText());fuhao="*";clear=false;}//除法运算bDivif (temp == bDiv){previous=Double.parseDouble(tf.getText());fuhao="/";clear=false;}//求余数if(temp == bPercent){previous=Double.parseDouble( tf.getText());fuhao="%";clear=false;}//等于if (temp==bEqual){try{next = Double.parseDouble(tf.getText());tf.setText("");if (fuhao =="+")tf.setText(previous + next +"");if(fuhao == "-")tf.setText(previous - next +"");if(fuhao == "*")tf.setText(previous * next +"");if(fuhao == "/")tf.setText(previous / next +"");if(fuhao == "%")tf.setText(previous % next +"");clear=false;}catch(Exception ex){tf.setText("请检查输入的数据:" + ex.getMessage()) ;clear=false;}}}public void mouseEntered(MouseEvent e){Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveIn);}if(temp==bSqrt){bSqrt.setBackground(cMoveIn);}if(temp==bPercent){bPercent.setBackground(cMoveIn);}if(temp==bC){bC.setBackground(cMoveIn);}if(temp==bBack){bBack.setBackground(cMoveIn);}if(temp==b7){b7.setBackground(cMoveIn);}if(temp==b8){b8.setBackground(cMoveIn);}if(temp==b9){b9.setBackground(cMoveIn);}if(temp==bDiv){bDiv.setBackground(cMoveIn);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveIn); }if(temp==b4){b4.setBackground(cMoveIn);}if(temp==b5){b5.setBackground(cMoveIn);}if(temp==b6){b6.setBackground(cMoveIn);}if(temp==bMulti){bMulti.setBackground(cMoveIn); }if(temp==bSin){bSin.setBackground(cMoveIn);}if(temp==b1){b1.setBackground(cMoveIn);}if(temp==b2){b2.setBackground(cMoveIn);}if(temp==b3){b3.setBackground(cMoveIn);}if(temp==bMinus){bMinus.setBackground(cMoveIn); }if(temp==bCos){bCos.setBackground(cMoveIn);}if(temp==b0){b0.setBackground(cMoveIn);}if(temp==bDot){bDot.setBackground(cMoveIn);}if(temp==bEqual){bEqual.setBackground(cMoveIn);}if(temp==bPlus){bPlus.setBackground(cMoveIn);}if(temp==bTan){bTan.setBackground(cMoveIn);}}public void mouseExited(MouseEvent e) {Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveOut);}if(temp==bSqrt){bSqrt.setBackground(cMoveOut);}if(temp==bPercent){bPercent.setBackground(cMoveOut);}if(temp==bC){bC.setBackground(cMoveOut);}if(temp==bBack){bBack.setBackground(cMoveOut);}if(temp==b7){b7.setBackground(cMoveOut);}if(temp==b8){b8.setBackground(cMoveOut);}if(temp==b9){b9.setBackground(cMoveOut);}if(temp==bDiv){bDiv.setBackground(cMoveOut);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveOut); }if(temp==b4){b4.setBackground(cMoveOut);}if(temp==b5){b5.setBackground(cMoveOut);}if(temp==b6){b6.setBackground(cMoveOut);}if(temp==bMulti){bMulti.setBackground(cMoveOut); }if(temp==bSin){bSin.setBackground(cMoveOut);}if(temp==b1){b1.setBackground(cMoveOut);}if(temp==b2){b2.setBackground(cMoveOut);}if(temp==b3){b3.setBackground(cMoveOut);}if(temp==bMinus){bMinus.setBackground(cMoveOut); }if(temp==bCos){bCos.setBackground(cMoveOut);}if(temp==b0){b0.setBackground(cMoveOut);}if(temp==bDot){bDot.setBackground(cMoveOut);}if(temp==bEqual){bEqual.setBackground(cMoveOut);}if(temp==bPlus){bPlus.setBackground(cMoveOut);}if(temp==bTan){bTan.setBackground(cMoveOut);}}public static void main(String args[]){Calc frame=new Calc();frame.display();}public void windowClosing(WindowEvent e){System.exit(0);}public void mouseClicked(MouseEvent arg0) {}public void mousePressed(MouseEvent arg0) {}public void mouseReleased(MouseEvent arg0) { }}。
package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。
function LXhf=figure('position',[200 200 700 480],...'Name','数独',...'NumberTitle','off');global ht_text;//可能出错for i=1:9for j=1:9ht_text(10-j,i)=uicontrol(hf,'Style','edit',...'Position',[50*i -30+50*j 30 30]);endendhbClose=uicontrol(hf,'Style','Pushbutton',...'Position',[550 200 100 50],...'String','Exit',...'CallBack','close(hf)');hbClear=uicontrol(hf,'Style','Pushbutton',...'Position',[550 300 100 50],...'String','Clear',...'CallBack',@Clear_string);hbStart=uicontrol(hf,'Style','Pushbutton',...'Position',[550 400 100 50],...'String','Start',...'CallBack',@string_start);hbHelp=uicontrol(hf,'Style','Text',...'Position',[520 30 170 150],...'String', [' 数独:每行,每列的取值为1~9且只能取一次',...'填数区域分为9个3*3的大区域,每个区域也只能取1~9个数,且只能取一次',...'在对应的方框内写入数值,无取值时,请不要输入内容'],...'FontName','宋体',...'FontSize',12);endfunction Clear_string(hObeject,eventdata,ht_text)global ht_text;for i=1:9for j=1:9set(ht_text(i,j),'String','');endendendfunction string_start(hObeject,eventdata,ht_text)global ht_text;num_a=zeros(9);for i=1:9for j=1:9if get(ht_text(i,j),'string')~=' 'flag_s=get(ht_text(i,j),'string');if (flag_s>='1')&(flag_s<='9')flag_s_num=str2double(flag_s);if (flag_s_num>=1)&(flag_s_num<=9)num_a(i,j)=str2double(get(ht_text(i,j),'string'));elsemsgbox('数独输入出错,请检查输入信息','错误警告');return;endelsemsgbox('数独输入出错,请检查输入信息','错误警告');return;endendendendstart(num_a);endfunction start(num_a)flag_error=0;for i=1:9flag_error=jiancha(num_a,'str_i',i,1);if flag_error==1msgbox('数独输入错误,请检查输入信息!','出错信息');break;endendif flag_error==0for j=1:9flag_error=jiancha(num_a,'str_j',1,j);if flag_error==1msgbox('数独输入错误,请检查输入信息!','出错信息');break;endendendif flag_error==0for i=1:3:9for j=1:3:9flag_error=jiancha(num_a,'str_s',i,j);if flag_error==1msgbox('数独输入错误,请检查输入信息!','出错信息');break;endendendendif flag_error==0flag_num=0;flag_num_num=0;[flag_num,flag_num_num]=jisuan(num_a,flag_num,flag_num_num);if flag_num==0msgbox('数独无解,请检查是否输入错误!','出错信息');endendendfunction [flag_num,flag_num_num]=jisuan(num_a,flag_num,flag_num_num) if flag_num_num==3return;endflag_flag_num=0;for i=1:9for j=1:9if num_a(i,j)==0flag_i=i;flag_j=j;flag_flag_num=1;break;endendif flag_flag_num==1;break;endendif i==9&&j==9&&flag_flag_num==0return;endstr_flag='str_i';num_i=rcs(num_a,str_flag,flag_i,flag_j);str_flag='str_j';num_j=rcs(num_a,str_flag,flag_i,flag_j);str_flag='str_s';num_s=rcs(num_a,str_flag,flag_i,flag_j);k=0;keyong=zeros(1,9);for i=num_ifor j=num_jif i==jfor ij=num_sif i==ijk=k+1;keyong(k)=i;endendendendendif k>0for i=1:kif keyong(i)~=0num_a(flag_i,flag_j)=keyong(i);elsecontinue;endif sum(sum(num_a))==405flag_num=flag_num+1;if flag_num==1 %flag_num数独解的个数print_num(num_a)elseif flag_num==2button=questdlg('数独有多解,是否查看其它解?','多解提示信息','Yes');switch buttoncase 'Yes'flag_num_num=1; %flag_num_num=1查看多组解记录num_acase 'No'flag_num_num=3; %flag_num_num=3不查看其它解return;case 'Cancel'flag_num_num=3 ;return;endelseif flag_num>2&&flag_num_num==1num_aelseif flag_num>2&&flag_num_num==3return;endend[flag_num,flag_num_num]=jisuan(num_a,flag_num,flag_num_num);endendendfunction num_f=rcs(num_a,str_flag,flag_flag_i,flag_flag_j)clear num_flagnum_flag=[1 2 3 4 5 6 7 8 9];switch str_flagcase 'str_i'for j=1:9switch num_a(flag_flag_i,j)case 1num_flag(1)=0;case 2num_flag(2)=0;case 3num_flag(3)=0;case 4num_flag(4)=0;case 5num_flag(5)=0;case 6num_flag(6)=0;case 7num_flag(7)=0;case 8num_flag(8)=0;case 9num_flag(9)=0;endendcase 'str_j'for i=1:9switch num_a(i,flag_flag_j)case 1num_flag(1)=0;case 2num_flag(2)=0;case 3num_flag(3)=0;case 4num_flag(4)=0;case 5num_flag(5)=0;case 6num_flag(6)=0;case 7num_flag(7)=0;case 8num_flag(8)=0;case 9num_flag(9)=0;endendcase 'str_s'if flag_flag_i<=3flag_i=[1 2 3];elseif flag_flag_i<=6flag_i=[4 5 6];elseflag_i=[7 8 9];endif flag_flag_j<=3flag_j=[1 2 3];elseif flag_flag_j<=6flag_j=[4 5 6];elseflag_j=[7 8 9];endfor i=flag_ifor j=flag_jswitch num_a(i,j)case 1num_flag(1)=0;case 2num_flag(2)=0;case 3num_flag(3)=0;case 4num_flag(4)=0;case 5num_flag(5)=0;case 6num_flag(6)=0;case 7num_flag(7)=0;case 8num_flag(8)=0;case 9num_flag(9)=0;endendendendk=0;for i=1:9if num_flag(i)~=0k=k+1;num_f(k)=num_flag(i);endendendfunction flag_error=jiancha(num_a,str_flag,flag_i,flag_j)flag_error=0;switch str_flagcase 'str_i'for i=1:9for j=i+1:9if num_a(flag_i,i)==num_a(flag_i,j)&&num_a(flag_i,i)~=0flag_error=1;return;endendendcase 'str_j'for i=1:9for j=i+1:9if num_a(i,flag_j)==num_a(j,flag_j)&&num_a(i,flag_j)~=0flag_error=1;return;endendendcase 'str_s'if flag_i<=3flag_ii=[1 2 3];elseif flag_i<=6flag_ii=[4 5 6];elseflag_ii=[7 8 9];endif flag_j<=3flag_jj=[1 2 3];elseif flag_j<=6flag_jj=[4 5 6];elseflag_jj=[7 8 9];endflag_num_a=[num_a(flag_ii(1),flag_jj(1)) num_a(flag_ii(2),flag_jj(1)) num_a(flag_ii(3),flag_jj(1))];flag_num_a=[flag_num_a num_a(flag_ii(1),flag_jj(2)) num_a(flag_ii(2),flag_jj(2)) num_a(flag_ii(3),flag_jj(2))];flag_num_a=[flag_num_a num_a(flag_ii(1),flag_jj(3)) num_a(flag_ii(2),flag_jj(3)) num_a(flag_ii(3),flag_jj(3))];for i=1:9for j=i+1:9if flag_num_a(i)==flag_num_a(j)&&flag_num_a(i)~=0flag_error=1;return;endendendendend。
计算器本计算器有显示过程和不显示过程两种功能,其中不显示过程为普通计算器,类似于windows自带的计算器;显示过程的,可以显示预算过程,其中包含所需应用的部分函数,以及格式化功能(最左上角,第一个键格式化,然后输入需要格式化的数位,然后点第二个数,显示格式化结果),当一次运算结束后,会在右边自动显示运算过程,并且运算过程处有保存,复制粘贴清除功能。
代码如下:主类:import ZF.*;public class JiSuanQi {public static void main(String[] args) {Calculator c = new Calculator("计算器");}}包ZF中的类:Calculator类package ZF;/*** 计算器布局界面*/import java.io.*;import java.awt.*;import javax.swing.*;import java.awt.event.*;public class Calculator extends JFrame implements ActionListener {static int xg = 1;// 用于判断是否显示过程,初始状态为显示JSplitPane jsp1, jsp2, jsp3;static JTextField jtf;// 文本框static JTextArea jta;// 保存等的历史文本区public static String zc;// 用来暂时存储数字,实现第一个菜单选项JScrollPane JS;// 专门用于给文本区提供滚动条public static FileDialog load, save;// 声明引入对话框BufferedReader in;//FileReader reader;//JP1 jp1;JP2 jp2;JP3 jp3;JP4 jp4;JP5 jp5;// 菜单条JMenuBar mb;JMenu m0, m1, m2;JMenuItem m01, m02, m03, m04, m11, m12, m21, m22;public Calculator(String s) {super(s);Container con = getContentPane();// 桌面jp1 = new JP1();jp2 = new JP2();jp3 = new JP3();jp4 = new JP4();jp5 = new JP5();jta = new JTextArea();jta.setEditable(false);JS = new JScrollPane(jta);jsp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp1, jp2);jsp2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp3, JS);jsp3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, jp4, jp5);jtf = new JTextField();jtf.setText(String.valueOf(0));jtf.setEditable(false);jtf.setBackground(Color.white);load = new FileDialog(this, "读取历史运算过程", FileDialog.LOAD);load.setVisible(false);load.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {load.setVisible(false);}});save = new FileDialog(this, "保存历史运算过程", FileDialog.SAVE); save.setVisible(false);save.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {save.setVisible(false);}});// 菜单条mb = new JMenuBar();m0 = new JMenu("编辑");m1 = new JMenu("查看");m2 = new JMenu("帮助");m01 = new JMenuItem("复制");m02 = new JMenuItem("粘贴");m03 = new JMenuItem("读取");m04 = new JMenuItem("关闭");m01.addActionListener(this);m02.addActionListener(this);m03.addActionListener(this);m04.addActionListener(this);m11 = new JMenuItem("不显过程");m12 = new JMenuItem("显示过程");m11.addActionListener(this);m12.addActionListener(this);m21 = new JMenuItem("帮助主题");m22 = new JMenuItem("关于计算器");m21.addActionListener(this);m22.addActionListener(this);m0.add(m01);m0.add(m02);m0.add(m03);m0.add(m04);m1.add(m11);m1.add(m12);m2.add(m21);m2.addSeparator();m2.add(m22);mb.add(m0);mb.add(m1);mb.add(m2);setJMenuBar(mb);con.add(jtf, BorderLayout.NORTH);con.add(jsp1, BorderLayout.CENTER);con.add(jsp2, BorderLayout.EAST);con.add(jsp3, BorderLayout.WEST);setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);setBounds(100, 100, 800, 260);setResizable(false);setVisible(true);validate();}public void actionPerformed(ActionEvent e) {if (!jtf.getText().equals("error")) {if (e.getSource() == m01) {zc = jtf.getText();} else if (e.getSource() == m02) {if (zc != null) {if (xg == 1) {if (jtf.getText().equals("0"))jtf.setText(zc);elsejtf.setText(jtf.getText() + zc);} elsejtf.setText(zc);}}}if (e.getSource() == m03) { //读取文件Calculator.load.setVisible(true);Calculator.jta.setText(null);String s;if(Calculator.load.getFile()!=null){try{File file=new File(Calculator.load.getDirectory(),Calculator.load.getFile());reader=new FileReader(file);in=new BufferedReader(reader);while((s=in.readLine())!=null){Calculator.jta.append(s+'\n');}in.close();reader.close();}catch(IOException e2){Calculator.jta.append("读取错误");}}} else if (e.getSource() == m04) {System.exit(0);} else if (e.getSource() == m11) {// 换窗体大小,同时换规则setSize(320, 260);remove(jsp2);remove(jsp3);JP2.sf = 0;jtf.setText(String.valueOf(0));xg = 0;// 改变菜单选项的可选性m03.setEnabled(false);m04.setEnabled(false);// 换对齐方式JP2.sf = 0;jtf.setEditable(false);jtf.setBackground(Color.white);jtf.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);validate();} else if (e.getSource() == m12) {setSize(800, 260);add(jsp2, BorderLayout.EAST);add(jsp3, BorderLayout.WEST);JP2.sf = 0;jtf.setText(String.valueOf(0));xg = 1;m03.setEnabled(true);m04.setEnabled(true);JP2.eg = 0;jtf.setEditable(false);jtf.setBackground(Color.white);jtf.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);validate();} else if (e.getSource() == m21) {JOptionPane.showMessageDialog(this,"本计算器以模仿Windows系统自带计算器为主,详情请参照系统计算器“帮助主题”。
本计算器相对来说比较完整,不能说没有bug,但是相对于网上下载的那些粗略的计算器要完整的多,如“.”,“0”的处理,网上的计算器代码可以出现“0123”,“.122”,“.0123”,“….114”,等关于“0”和“.”的各种问题,而本代码对这方面做了完整的处理。
1. Calculator 类import java.applet.*;import java.awt.*;import java.awt.event.*;import ng.*;import java.applet.Applet;import javax.swing.*;import javax.swing.border.*;public class Calculator extends JApplet implements ActionListener{private final String[] KEYS={"7","8","9","/","sqrt", "4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};private final String[] COMMAND={"Backspace","CE","C"};private final String[] M={" ","MC","MR","MS","M+"};private JButton keys[]=new JButton[KEYS.length];private JButton commands[]=new JButton[COMMAND.length];private JButton m[]=new JButton[M.length];private JTextField display =new JTextField("0");// public JTextField setHorizontalAlignment(int alignment);// private JTextFielddisplay.setHorizontalAlignment(JTextField.RIGHT)=new JTextField("0"); private void setup(){display.setHorizontalAlignment(JTextField.RIGHT);JPanel calckeys=new JPanel();JPanel command=new JPanel();JPanel calms=new JPanel();calckeys.setLayout(new GridLayout(4,5,3,3));command.setLayout(new GridLayout(1,3,3,3));calms.setLayout(new GridLayout(5,1,3,3));for(int i=0;i<KEYS.length;i++){keys[i]=new JButton(KEYS[i]);calckeys.add(keys[i]);keys[i].setForeground(Color.blue);}keys[3].setForeground(Color.red);keys[4].setForeground(Color.red);keys[8].setForeground(Color.red);keys[9].setForeground(Color.red);keys[13].setForeground(Color.red);keys[14].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);for(int i=0;i<COMMAND.length;i++){commands[i]=new JButton(COMMAND[i]);command.add(commands[i]);commands[i].setForeground(Color.red);}for(int i=0;i<M.length;i++){m[i]=new JButton(M[i]);calms.add(m[i]);m[i].setForeground(Color.red);}JPanel panel1=new JPanel();panel1.setLayout(new BorderLayout(3,3));panel1.add("North",command);panel1.add("Center",calckeys);JPanel top=new JPanel();top.setLayout(new BorderLayout());display.setBackground(Color.WHITE);top.add("Center",display);getContentPane().setLayout(new BorderLayout(3,5)); getContentPane().add("North",top);getContentPane().add("Center",panel1);getContentPane().add("West",calms);}public void init(){setup();for(int i=0;i<KEYS.length;i++){keys[i].addActionListener(this);}for(int i=0;i<COMMAND.length;i++){commands[i].addActionListener(this);}for(int i=0;i<M.length;i++){m[i].addActionListener(this);}display.setEditable(false);}public void actionPerformed(ActionEvent e){String label=e.getActionCommand();// double zero=e.getActionCommand();if(label=="C")handleC();else if(label=="Backspace")handleBackspace();else if(label=="CE")display.setText("0");else if (label=="1/x")daoShu();else if(label=="sqrt"){display.setText(Math.sqrt(getNumberFromDisplay())+""); }else if("0123456789.".indexOf(label)>=0){handleNumber(label);// handlezero(zero);}elsehandleOperator(label);}private boolean firstDigit=true;private void handleNumber(String key){if(firstDigit){ if(key.equals("0"))display.setText(key);else if(key.equals(".")){display.setText("0.");firstDigit=false;}else if(!key.equals("0")&&!key.equals(".")){display.setText(key);firstDigit=false;}}else if((key.equals("."))&&(display.getText().indexOf(".")<0))display.setText(display.getText()+".");else if(!key.equals(".")&&display.getText().length()<=32) display.setText(display.getText()+key);}private double number=0;private String operator="=";private void handleOperator(String key){if(operator.equals("/")){if(getNumberFromDisplay()==0){display.setText("除数不能为零");}else{number/=getNumberFromDisplay();}long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0){display.setText(String.valueOf(t1));}else{display.setText(String.valueOf(number));}}else if(operator.equals("+"))number+=getNumberFromDisplay();else if(operator.equals("-"))number-=getNumberFromDisplay();else if(operator.equals("*"))number*=getNumberFromDisplay();else if(operator.equals("%"))number=number/100;else if(operator.equals("+/-"))number=number*(-1);else if(operator.equals("="))number=getNumberFromDisplay();long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0)display.setText(String.valueOf(t1));elsedisplay.setText(String.valueOf(number));operator=key;firstDigit=true;}private double getNumberFromDisplay(){return Double.valueOf(display.getText()).doubleValue(); }private void handleC(){display.setText("0");firstDigit=true;operator="=";}private void handleBackspace(){String text=display.getText();int i=text.length();if(i>0){text=text.substring(0,i-1);if(text.length()==0){display.setText("0");firstDigit=true;operator="=";}elsedisplay.setText(text);}}private void daoShu(){if (display.getText().equals("0")) {display.setText("除数不能为零");System.out.println(1);}else{long l;double d=1/getNumberFromDisplay();l=(long)d;System.out.println(d);System.out.println(l);display.setText(String.valueOf(d));}}}2.CalFrame 类import java.awt.Color;importimport java.awt.event.ActionListener; import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JApplet;import javax.swing.JFrame;public class Test {public static void main(String[] args) {JFrame f=new JFrame();f.getAccessibleContext();Calculator Calculator1=new Calculator(); Calculator1.init();f.getContentPane().add("Center",Calculator1);f.setVisible(true);f.setBounds(300, 200,380,245);f.setBackground(Color.LIGHT_GRAY);f.validate();f.setResizable(false);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});f.setTitle("计算器");}}。
计算器源代码一、计算器源代码文件名:computer1.javaimport java.awt.*;import java.awt.event.*;public class computer1 extends Frame implements ActionListener{//声明窗口类并实现动作事件接口。
Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9;//声明数字按钮Button op,os,om,od,oe,oc;//声明操作按钮TextField tfd;//声明文本框String flg,rslt;//声明标志串、结果串Panel p1,p2,p3;//声明面板int i1,i2;float flt;computer1(){super("加减乘除计算器");n0 = new Button("0");//实现各按钮n1 = new Button("1");n2 = new Button("2");n3 = new Button("3");n4 = new Button("4");n5 = new Button("5");n6 = new Button("6");n7 = new Button("7");n8 = new Button("8");n9 = new Button("9");op = new Button("加");os = new Button("减");om = new Button("乘");od = new Button("除");oe = new Button("=");oc = new Button("c");tfd = new TextField(20);//实现文本框p1=new Panel();//实现各面板p2=new Panel();p3=new Panel();setLayout(new FlowLayout());//布局设计,用于安排按钮位置p1.add(n0);//将各数字按钮放入p1中p1.add(n1);p1.add(n2);p1.add(n3);p1.add(n4);p1.add(n5);p1.add(n6);p1.add(n7);p1.add(n8);p1.add(n9);p2.add(op);//将各操作按钮放入p2、p3中p2.add(os);p2.add(om);p2.add(od);p3.add(oe);p3.add(oc);setLayout(new BorderLayout());//布局设计,用于安排面板位置add("North",tfd);add("West",p1);add("Center",p2);add("East",p3);n0.addActionListener(this);//注册监听器到各按钮n1.addActionListener(this);n2.addActionListener(this);n3.addActionListener(this);n4.addActionListener(this);n5.addActionListener(this);n6.addActionListener(this);n7.addActionListener(this);n8.addActionListener(this);n9.addActionListener(this);op.addActionListener(this);os.addActionListener(this);om.addActionListener(this);od.addActionListener(this);oe.addActionListener(this);oc.addActionListener(this);addWindowListener(new closeWin());setSize(600,100);//确定窗口的尺寸setVisible(true);}public static void main (String args[]){new computer1();}public void actionPerformed(ActionEvent e){//处理鼠标事件的方法try{//异常处理if(e.getSource()==n0)//按数字键时tfd.setText(tfd.getText()+"0");if(e.getSource()==n1)tfd.setText(tfd.getText()+"1");if(e.getSource()==n2)tfd.setText(tfd.getText()+"2");if(e.getSource()==n3)tfd.setText(tfd.getText()+"3");if(e.getSource()==n4)tfd.setText(tfd.getText()+"4");if(e.getSource()==n5)tfd.setText(tfd.getText()+"5");if(e.getSource()==n6)tfd.setText(tfd.getText()+"6");if(e.getSource()==n7)tfd.setText(tfd.getText()+"7");if(e.getSource()==n8)tfd.setText(tfd.getText()+"8");if(e.getSource()==n9)tfd.setText(tfd.getText()+"9");if(e.getSource()==op){//按加号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "op";}if(e.getSource()==os){//按减号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "os";}if(e.getSource()==om){//按乘号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "om";}if(e.getSource()==od){//按除号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "od";}if(e.getSource()==oe){//按等号键时i2 = Integer.parseInt(tfd.getText());if(flg=="op"){rslt=Integer.toString(i1+i2);}if(flg=="os"){rslt=Integer.toString(i1-i2);}if(flg=="om"){rslt=Integer.toString(i1*i2);}if(flg=="od"){//除法需做小数处理flt=((float)i1)/((float)i2);rslt=Float.toString(flt);}tfd.setText(rslt);}if(e.getSource()==oc){//按清除键时tfd.setText("");flg = "";}}catch(Exception ex){}//扑捉到异常,但不进行处理}}class closeWin extends WindowAdapter{ //关闭窗口public void windowClosing(WindowEvent e){Frame frm=(Frame)(e.getSource());frm.dispose();System.exit(0);}}二、计算器界面三、修改后计算器界面。
java简单计算器代码Java简单计算器代码:```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner input = new Scanner(System.in);double num1, num2, result = 0;char operator;System.out.print("请输入第一个数:");num1 = input.nextDouble();System.out.print("请输入运算符号(+、-、*、/):"); operator = input.next().charAt(0);System.out.print("请输入第二个数:");num2 = input.nextDouble();switch(operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':result = num1 / num2;break;default:System.out.println("运算符输入错误,请重新输入!");return;}System.out.println("运算结果:" + num1 + operator + num2 + "=" + result);}}```列表:1. 首先,在程序中导入`java.util.Scanner`包,以便从控制台读取用户输入内容。
计算器程序的源代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{private Container container;private GridBagLayout layout;private GridBagConstraints constraints;private JTextField displayField; //计算结果显示区private String lastCommand; //保存+,-,*,/,=命令0private double result; //保存计算结果private boolean start; //判断是否为数字的开始private JMenuBar menubar;private JMenuItem m_exit,m2_ejz,m2_bjz;private Dialog dialog;private Label label_dialog;private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0, button_plus,button_minus,button_multiply,button_divide,button_point,button_equal,button_log,button_tan,button_cos,button_sin,button_exp;public Calculator() //构造方法设置布局、为按钮注册事件监听器{super("Calculator");this.setLocation(240,200);this.setSize(350,300);this.setResizable(true);this.setLayout(new GridLayout(7,1));this.addmyMenu(); //调用成员方法添加菜单displayField=new JTextField(30);this.add(displayField);displayField.setEditable(true);start=true;result=0;lastCommand = "=";JPanel panel0=new JPanel();panel0.setLayout(new GridLayout(1,4,4,4));JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(1,5,4,4));this.add(panel1);button_sqrt=new JButton("sqrt");button_plusminus=new JButton("+/-");button_exp=new JButton("exp");button_CE=new JButton("C");button_cancel=new JButton("CE");JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,5,4,4));this.add(panel2);button_7=new JButton("7");button_8=new JButton("8");button_9=new JButton("9");button_log=new JButton("log");button_divide=new JButton("/");JPanel panel3=new JPanel();panel3.setLayout(new GridLayout(1,5,4,4));this.add(panel3);button_4=new JButton("4");button_5=new JButton("5");button_6=new JButton("6");button_tan=new JButton("tan");button_multiply=new JButton("*");JPanel panel4=new JPanel();panel4.setLayout(new GridLayout(1,5,4,4));this.add(panel4);button_1=new JButton("1");button_2=new JButton("2");button_3=new JButton("3");button_cos=new JButton("cos");button_minus=new JButton("-");JPanel panel5=new JPanel();panel5.setLayout(new GridLayout(1,5,4,4));this.add(panel5);button_0=new JButton("0");button_point=new JButton(".");button_equal=new JButton("=");button_sin=new JButton("sin");button_plus=new JButton("+");panel1.add(button_sqrt);panel1.add(button_plusminus);panel1.add(button_exp);panel1.add(button_CE);panel1.add(button_cancel);panel2.add(button_7);panel2.add(button_8);panel2.add(button_9);panel2.add(button_log);panel2.add(button_divide);panel3.add(button_4);panel3.add(button_5);panel3.add(button_6);panel3.add(button_tan);panel3.add(button_multiply);panel4.add(button_1);panel4.add(button_2);panel4.add(button_3);panel4.add(button_cos);panel4.add(button_minus);panel5.add(button_0);panel5.add(button_point);panel5.add(button_equal);panel5.add(button_sin);panel5.add(button_plus);button_sqrt.addActionListener(this);button_plusminus.addActionListener(this);button_exp.addActionListener(this);button_CE.addActionListener(this);button_cancel.addActionListener(this);button_7.addActionListener(this);button_8.addActionListener(this);button_9.addActionListener(this);button_log.addActionListener(this);button_divide.addActionListener(this);button_4.addActionListener(this);button_5.addActionListener(this);button_6.addActionListener(this);button_tan.addActionListener(this);button_multiply.addActionListener(this);button_1.addActionListener(this);button_2.addActionListener(this);button_3.addActionListener(this);button_cos.addActionListener(this);button_minus.addActionListener(this);button_0.addActionListener(this);button_point.addActionListener(this);button_equal.addActionListener(this);button_sin.addActionListener(this);button_plus.addActionListener(this);this.addWindowListener(new WinClose()); //注册窗口监听器this.setVisible(true);}private void addmyMenu() //菜单的添加{JMenuBar menubar=new JMenuBar();this.add(menubar);JMenu m1=new JMenu("选项");JMenu m2=new JMenu("进制转换");JMenuItem m1_exit=new JMenuItem("退出");m1_exit.addActionListener(this);JMenuItem m2_ejz=new JMenuItem("二进制");m2_ejz.addActionListener(this);JMenuItem m2_bjz=new JMenuItem("八进制");m2_bjz.addActionListener(this);JMenu m3 = new JMenu(" 帮助");JMenuItem m3_Help = new JMenuItem("作者");m3_Help.addActionListener(this);dialog = new Dialog(this,"关于",true); //模式窗口 dialog.setSize(240,80);label_dialog = new Label("",Label.CENTER); //标签的字符串为空,居中对齐dialog.add(label_dialog);dialog.addWindowListener(this); //为对话框注册窗口事件监听器m1.add(m1_exit);menubar.add(m1);m2.add(m2_ejz);m2.add(m2_bjz);menubar.add(m2);m3.add(m3_Help);menubar.add(m3); }public void actionPerformed(ActionEvent e) //按钮的单击事件处理方法{if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||e.getSource().equals(button_3)||e.getSource().equals(button_4)||e.getSource().equals(button_5)|| e.getSource().equals(button_6)||e.getSource().equals(button_7)|| e.getSource().equals(button_8)||e.getSource().equals(button_9) ||e.getSource().equals(button_0)||e.getSource().equals(button_point)||e.getSource().equals(button_plusmin us)||e.getSource().equals(button_cancel)||e.getSource().equals(button_CE)){ //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getText()+"-");}if(!input.equals("+/-")){String str=displayField.getText();if(input.equals("C")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("CE")) //清零键的实现方法{displayField.setText("0");start=true;}elsedisplayField.setText(displayField.getText()+input);}}else if (e.getActionCommand()=="二进制") //二进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toBinaryString(n));}else if (e.getActionCommand()=="八进制") //八进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toOctalString(n));}else if (e.getActionCommand()=="退出") //选项中退出的处理方法{System.exit(0);}else if (e.getActionCommand()=="作者") //按下'帮助'菜单栏中用法的处理方法{label_dialog.setText("熊瑛琪制作 \n学号:080320618");dialog.setLocation(400,250);dialog.setVisible(true);}else //各运算符的识别{String command=e.getActionCommand();if(start){lastCommand=command;}else{calculate(Double.parseDouble(displayField.getText()));lastCommand=command;start=true;}}}public void calculate(double x) //各运算符的具体运算方法 {double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}displayField.setText(""+ result);}public void windowClosing(WindowEvent e){if(e.getSource()==dialog)dialog.setVisible(false); //隐藏对话框elseSystem.exit(0);}public void windowOpened(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public static void main(String args[]){Calculator calculator=new Calculator();}}class WinClose implements WindowListener{public void windowClosing(WindowEvent e) //单击窗口关闭按钮时触发并执行实现窗口监听器接口{System.exit(0); //结束程序运行}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}程序运行在对程序进行测试时发现“sin”函数出现异常点击“sin”然后输入“90”出现以下情况经过对程序代码的检查发现在下面方法中public void calculate(double x) //各运算符的具体运算方法{double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}displayField.setText(""+ result); }发现遗漏以下代码else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}修改后再次进行测试输入“1.5707963”(约为0.5*pi)再键入“sin”得以下结果可见程序修改成功。
java简易计算机代码Java是一种面向对象的编程语言,广泛应用于计算机编程领域。
下面我们来看一段简易的Java代码,实现一个计算器的功能。
我们需要定义一个Calculator类,代码如下:```javapublic class Calculator {// 定义两个整型变量,用于存储输入的数字private int num1;private int num2;// 构造方法,用于初始化Calculator对象public Calculator(int num1, int num2) {this.num1 = num1;this.num2 = num2;}// 加法运算方法public int add() {return num1 + num2;}// 减法运算方法public int subtract() {return num1 - num2;}// 乘法运算方法public int multiply() {return num1 * num2;}// 除法运算方法public double divide() {// 判断除数是否为0,避免除以0的错误if (num2 != 0) {return (double)num1 / num2;} else {System.out.println("除数不能为0!");return 0;}}// 主方法,程序入口public static void main(String[] args) {// 创建一个Calculator对象,传入两个待计算的数值Calculator calculator = new Calculator(10, 5);// 调用加法运算方法,并输出结果int sum = calculator.add();System.out.println("两数之和:" + sum);// 调用减法运算方法,并输出结果int difference = calculator.subtract();System.out.println("两数之差:" + difference);// 调用乘法运算方法,并输出结果int product = calculator.multiply();System.out.println("两数之积:" + product);// 调用除法运算方法,并输出结果double quotient = calculator.divide();if (quotient != 0) {System.out.println("两数之商:" + quotient);}}}```在上面的代码中,我们首先定义了一个Calculator类,包含了两个私有的整型变量num1和num2,用于存储输入的数字。
/*这是本人最近做的一个数独计算器程序。
1.该程序由java编写。
2.该程序具有界面3.把以下代码复制到记事本上保存为java文件。
4.javac Test8.java ,然后再java Test8,你懂的。
5.再图形中输入已知的数字,点击确定,图形中就会出现解。
*/import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import java.util.Iterator;import java.util.TreeSet;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;class Myframe extends JFrame{public static Object obj=new Object();public final static JTextField[][] filed=new JTextField[9][9]; public Myframe(){for(int a=0;a<9;a++){for(int b=0;b<9;b++){filed[a][b]=new JTextField();filed[a][b].setText("");}}JPanel jpan=new JPanel();jpan.setLayout(new GridLayout(9,9));for(int a=8;a>-1;a--){for(int b=0;b<9;b++){jpan.add(filed[b][a]);}}add(jpan,BorderLayout.CENTER);JPanel jpb=new JPanel();JButton button=new JButton("确定");jpb.add(button);button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){synchronized (obj) {for(int a=0;a<9;a++){for(int b3=0;b3<9;b3++){int pp=0;if(!(filed[a][b3].getText().trim().equals(""))){pp=Integer.parseInt(filed[a][b3].getText().trim());Jieda.b[a][b3]=pp;}}}}synchronized (obj) {new Thread(new Jieda()).start();}}});add(jpb,BorderLayout.SOUTH);}}public class Test8{public static void main(String[] args) {Myframe myf=new Myframe();myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);myf.setTitle("数独");myf.setSize(500,500);myf.setVisible(true);}}class Jieda implements Runnable{public static boolean[][] boo=new boolean[9][9];public static int shanghang=0;public static int shanglie=0;public static int[][] b=new int[9][9];public static void Huigui(boolean[][] boo1,int hang,int lie){int s=lie*9+hang;s--;int shang=s/9;int yushu=s%9;if(boo1[yushu][shang]){Huigui(boo1,yushu,shang);}else{shanghang=yushu;shanglie=shang;}}public static void arrayAdd(ArrayList<Integer> array,TreeSet<Integer> tree){for(int z=1;z<10;z++){boolean flag3=true;Iterator<Integer> it=tree.iterator();while(it.hasNext()){//10int b=it.next().intValue();if(z==b){flag3=false;break;}}if(flag3){array.add(new Integer(z));}flag3=true;}}public static ArrayList<Integer> Maybe(int hang,int lie){ ArrayList<Integer> array=new ArrayList<Integer>();TreeSet<Integer> tree=new TreeSet<Integer>();if(0<=hang&&hang<=2&&0<=lie&&lie<=2){for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(0<=hang&&hang<=2&&3<=lie&&lie<=5){for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(0<=hang&&hang<=2&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&0<=lie&&lie<=2){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}for(int a2=3;a2<6;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&3<=lie&&lie<=5){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=3;a2<6;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=3;a2<6;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&0<=lie&&lie<=2){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&3<=lie&&lie<=5){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}return array;}public void run() {for(int a=0;a<9;a++){for(int b1=0;b1<9;b1++){if(b[a][b1]!=0){boo[a][b1]=true;}else{boo[a][b1]=false;}}}boolean flag=true;ArrayList<Integer>[][] yinyong=new ArrayList[9][9]; int hang=0;int lie=0;while(lie<9){if(flag==true){hang=0;}while(hang<9){if(b[hang][lie]==0){if(flag){ArrayList<Integer> list=Maybe(hang,lie);yinyong[hang][lie]=list;}if(yinyong[hang][lie].isEmpty()){Huigui(boo,hang,lie);hang=shanghang;lie=shanglie;b[hang][lie]=0;lie--;flag=false;break;}//if(list.isEmpty())else{b[hang][lie]=yinyong[hang][lie].get(0);yinyong[hang][lie].remove(0);flag=true;boolean r=true;for(int a1=0;a1<9;a1++){for(int b1=0;b1<9;b1++){if(r==false){break;}if(b[a1][b1]==0){r=false;}}}if(r){for(int a1=0;a1<9;a1++){for(int b1=0;b1<9;b1++){System.out.print("b["+a1+"]["+b1+"]"+b[a1][b1]+","); Myframe.filed[a1][b1].setText(b[a1][b1]+"");}}}}}//if(int[hang][lie]==0)else{flag=true;}hang++;}lie++;}}}。
java程序计算数独游戏兴趣来了,写了个简单的数独游戏计算程序,未做算法优化。
通过⽂件来输⼊⼀个⼆维数组,9⾏,每⾏9个数组,数独游戏中需要填空的地⽅⽤0来表⽰。
结果也是打印⼆维数组。
1import java.io.File;2import java.util.List;3//代表数独中的⼀个单元格位置4public class Cell {56// 所在⾏7public int row;8// 所在列9public int colum;10// 值11public int value;1213public static int rowMax = 9;1415public static int columMax = 9;1617public static Cell[][] pan = new Cell[rowMax][columMax];1819// 初期化数独游戏20public static void init() {21// 数独盘上的值输⼊下⾯⽂件中,共9⾏,每⾏9个数字22// 0表⽰需要计算的空着的区域,23// eg:24// -----------------------25// 00830910026// 90006000427// 00750480028// 03600054029// 00100060030// 04200097031// 00590730032// 60001000833// 00460820034// -------------------------35 File f = new File("conf/sd.txt");36 List<List<Integer>> list = SDUtil.initQiPan(f);37for (int i = 0; i < rowMax; i++) {38for (int j = 0; j < columMax; j++) {39 pan[i][j] = new Cell(i, j);40 pan[i][j].value = list.get(i).get(j);41 }42 }43 }4445// 取得下⼀个需要计算的位置46public Cell getNext() {47 Cell next = null;48int row = 0;49int colum = 0;50if (this.row + 1 < rowMax) {51 row = this.row + 1;52 colum = this.colum;53 } else if (this.colum + 1 < columMax) {54 row = 0;55 colum = this.colum + 1;56 } else {57return null;58 }59 next = pan[row][colum];60return next;61 }6263private Cell(int row, int colum) {64this.row = row;65this.colum = colum;66 }6768 }1import java.io.BufferedReader;2import java.io.File;3import java.io.FileReader;4import java.util.ArrayList;5import java.util.List;67public class SDUtil {89//把配置⽂件转换成⼆维列表10public static List<List<Integer>> initQiPan(File f) {11 List<List<Integer>> list = new ArrayList<List<Integer>>();12try {13 BufferedReader br = new BufferedReader(new FileReader(f));14 String s;15while ((s = br.readLine()) != null) {16 s = s.trim();17char[] car = s.toCharArray();18 List<Integer> l = new ArrayList<Integer>();19for (int i = 0; i < 9; i++) {20 l.add(Integer.parseInt("" + car[i]));21 }22 list.add(l);23 }24 br.close();25 } catch (Exception e) {26 e.printStackTrace();27 }28return list;29 }30 }1import java.util.ArrayList;2import java.util.Arrays;3import java.util.List;45public class ShuDu {67static List<String> allNum = Arrays.asList("1", "2", "3", "4", "5", "6", 8 "7", "8", "9");910public static void main(String[] args) {11 begin();1213 }1415public static void begin() {16//初期化,数独中原有的数字装⼊17 Cell.init();18//第⼀个位置取得19 Cell beginCell = Cell.pan[0][0];20//计算21 insertCell(beginCell);22 }2324//打印结果25public static void printOkValue() {26for (int i = 0; i < Cell.rowMax; i++) {27for (int j = 0; j < Cell.columMax; j++) {28 System.out.print(Cell.pan[i][j].value + " ");29 }30 System.out.println();31 }32 }3334//计算并插⼊正确的值(主要逻辑⽅法)35public static boolean insertCell(Cell cell) {36if (cell.value == 0) {37 List<String> canList = getCanInList(cell.row, cell.colum);38if (canList.size() == 0) {39return false;40 }41for (String can : canList) {42 cell.value = Integer.parseInt(can);43 Cell nextCell = cell.getNext();44if (nextCell != null) {45boolean b = insertCell(nextCell);46if (b) {47return true;48 }49 } else {50 printOkValue();51 System.exit(0);52 ;53 }54 }55 cell.value = 0;56 } else {57 Cell nextCell = cell.getNext();58if (nextCell != null) {59boolean b = insertCell(nextCell);60if (b) {61return true;62 }63 } else {64 printOkValue();65 System.exit(0);66 ;67 }68 }6970return false;71 }7273//取得所在位置的所有可能数字列表74public static List<String> getCanInList(int row, int colum) {75 List<String> canList = new ArrayList<String>();76 canList.addAll(allNum);77 lineValidate(canList, row, colum, Cell.columMax);78 columValidate(canList, row, colum, Cell.rowMax);79 blockValidate(canList, row, colum);80return canList;81 }8283//⾏验证84public static void lineValidate(List<String> set, int row, int colum,85int max) {86for (int i = 0; i < max; i++) {87 String value = Cell.pan[row][i].value + "";88if (value.equals("0")) {89continue;90 }91 set.remove(value);92 }93 }9495//列验证96public static void columValidate(List<String> set, int row, int colum,97int max) {98for (int i = 0; i < max; i++) {99 String value = Cell.pan[i][colum].value + "";100if (value.equals("0")) {101continue;102 }103 set.remove(value);104 }105 }106107//所求位置所在的9个块验证108public static void blockValidate(List<String> canList, int row, int colum) { 109int blockRow = row / 3 * 3;110int blockColum = colum / 3 * 3;111for (int i = 0 + blockRow; i < 3 + blockRow; i++) {112for (int j = 0 + blockColum; j < 3 + blockColum; j++) {113 String value = Cell.pan[i][j].value + "";114if (value.equals("0")) {115continue;116 }117 canList.remove(value);118 }119 }120 }121 }。
/*这是本人最近做的一个数独计算器程序。
1.该程序由java编写。
2.该程序具有界面3.把以下代码复制到记事本上保存为java文件。
4.javac Test8.java ,然后再java Test8,你懂的。
5.再图形中输入已知的数字,点击确定,图形中就会出现解。
*/import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import java.util.Iterator;import java.util.TreeSet;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;class Myframe extends JFrame{public static Object obj=new Object();public final static JTextField[][] filed=new JTextField[9][9]; public Myframe(){for(int a=0;a<9;a++){for(int b=0;b<9;b++){filed[a][b]=new JTextField();filed[a][b].setText("");}}JPanel jpan=new JPanel();jpan.setLayout(new GridLayout(9,9));for(int a=8;a>-1;a--){for(int b=0;b<9;b++){jpan.add(filed[b][a]);}}add(jpan,BorderLayout.CENTER);JPanel jpb=new JPanel();JButton button=new JButton("确定");jpb.add(button);button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent event){synchronized (obj) {for(int a=0;a<9;a++){for(int b3=0;b3<9;b3++){int pp=0;if(!(filed[a][b3].getText().trim().equals(""))){pp=Integer.parseInt(filed[a][b3].getText().trim());Jieda.b[a][b3]=pp;}}}}synchronized (obj) {new Thread(new Jieda()).start();}}});add(jpb,BorderLayout.SOUTH);}}public class Test8{public static void main(String[] args) {Myframe myf=new Myframe();myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);myf.setTitle("数独");myf.setSize(500,500);myf.setVisible(true);}}class Jieda implements Runnable{public static boolean[][] boo=new boolean[9][9];public static int shanghang=0;public static int shanglie=0;public static int[][] b=new int[9][9];public static void Huigui(boolean[][] boo1,int hang,int lie){int s=lie*9+hang;s--;int shang=s/9;int yushu=s%9;if(boo1[yushu][shang]){Huigui(boo1,yushu,shang);}else{shanghang=yushu;shanglie=shang;}}public static void arrayAdd(ArrayList<Integer> array,TreeSet<Integer> tree){for(int z=1;z<10;z++){boolean flag3=true;Iterator<Integer> it=tree.iterator();while(it.hasNext()){//10int b=it.next().intValue();if(z==b){flag3=false;break;}}if(flag3){array.add(new Integer(z));}flag3=true;}}public static ArrayList<Integer> Maybe(int hang,int lie){ ArrayList<Integer> array=new ArrayList<Integer>();TreeSet<Integer> tree=new TreeSet<Integer>();if(0<=hang&&hang<=2&&0<=lie&&lie<=2){for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(0<=hang&&hang<=2&&3<=lie&&lie<=5){for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(0<=hang&&hang<=2&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=0;a2<3;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&0<=lie&&lie<=2){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}for(int a2=3;a2<6;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&3<=lie&&lie<=5){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=3;a2<6;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(3<=hang&&hang<=5&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=3;a2<6;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&0<=lie&&lie<=2){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=0;b4<3;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&3<=lie&&lie<=5){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=3;b4<6;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}else if(6<=hang&&hang<=8&&6<=lie&&lie<=8){ for(int a=0;a<9;a++){if(a!=lie&&b[hang][a]!=0){tree.add(new Integer(b[hang][a]));}}for(int b1=0;b1<9;b1++){if(b1!=hang&&b[b1][lie]!=0){tree.add(new Integer(b[b1][lie]));}}for(int a2=6;a2<9;a2++){for(int b4=6;b4<9;b4++){if((!(a2==hang&&b4==lie))&&b[a2][b4]!=0){tree.add(new Integer(b[a2][b4]));}}}arrayAdd(array,tree);}return array;}public void run() {for(int a=0;a<9;a++){for(int b1=0;b1<9;b1++){if(b[a][b1]!=0){boo[a][b1]=true;}else{boo[a][b1]=false;}}}boolean flag=true;ArrayList<Integer>[][] yinyong=new ArrayList[9][9]; int hang=0;int lie=0;while(lie<9){if(flag==true){hang=0;}while(hang<9){if(b[hang][lie]==0){if(flag){ArrayList<Integer> list=Maybe(hang,lie);yinyong[hang][lie]=list;}if(yinyong[hang][lie].isEmpty()){Huigui(boo,hang,lie);hang=shanghang;lie=shanglie;b[hang][lie]=0;lie--;flag=false;break;}//if(list.isEmpty())else{b[hang][lie]=yinyong[hang][lie].get(0);yinyong[hang][lie].remove(0);flag=true;boolean r=true;for(int a1=0;a1<9;a1++){for(int b1=0;b1<9;b1++){if(r==false){break;}if(b[a1][b1]==0){r=false;}}}if(r){for(int a1=0;a1<9;a1++){for(int b1=0;b1<9;b1++){System.out.print("b["+a1+"]["+b1+"]"+b[a1][b1]+","); Myframe.filed[a1][b1].setText(b[a1][b1]+"");}}}}}//if(int[hang][lie]==0)else{flag=true;}hang++;}lie++;}}}。