當前位置:首頁 » 編程語言 » 簡單的java計算器

簡單的java計算器

發布時間: 2022-06-04 08:42:48

1. java簡單計算器

import java.util.Scanner;

public class Calculator {
@SuppressWarnings("resource")
public static void main(String[] args) {
System.out.println("+------------------+");
System.out.println("| JAVA計算器例子 |");
System.out.println("+------------------+");
System.out.println("規則:操作數必須為整數,若除法運算則除數不能為零,");
System.out.println("運算符必須為'+,-,*,%'中的一種");
while (true) {
System.out.println("+-------------------------------------------+");
System.out.println("| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |");
System.out.println("+-------------------------------------------+");
System.out.println("請輸入您的選擇:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if ("0".equals(input)) {
System.exit(0);
break;
} else {
calculation(input);
}
}
}
@SuppressWarnings("resource")
private static void calculation(String param) {
System.out.println("請輸入第一個數字:");
Scanner scanner1 = new Scanner(System.in);
int num1 = scanner1.nextInt();
System.out.println("請輸入第二個數字(如果是除法,不能輸入0):");
Scanner scanner2 = new Scanner(System.in);
int num2 = scanner2.nextInt();
switch (param) {
case "1" :
System.out.println("本次的計算結果為:" + (num1 + num2));
break;
case "2" :
System.out.println("本次的計算結果為:" + (num1 - num2));
break;
case "3" :
System.out.println("本次的計算結果為:" + (num1 * num2));
break;
case "4" :
if (num2 == 0) {
System.out.println("除數為零,計算失敗!!!");
} else {
System.out.println("本次的計算結果為:" + (num1 / num2));
}
break;
default :
System.out.println("輸入有誤,請重新輸入。");
break;
}
}
}
上面是我寫的代碼,麻煩您看一下是否能滿足要求。
下面是執行的結果:
+------------------+
| JAVA計算器例子 |
+------------------+
規則:操作數必須為整數,若除法運算則除數不能為零,
運算符必須為'+,-,*,%'中的一種
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
1
請輸入第一個數字:
3
請輸入第二個數字(如果是除法,不能輸入0):
4
本次的計算結果為:7
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
5
請輸入第一個數字:
0
請輸入第二個數字(如果是除法,不能輸入0):
6
輸入有誤,請重新輸入。
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
4
請輸入第一個數字:
6
請輸入第二個數字(如果是除法,不能輸入0):
3
本次的計算結果為:2
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
2
請輸入第一個數字:
7
請輸入第二個數字(如果是除法,不能輸入0):
2
本次的計算結果為:5
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
3
請輸入第一個數字:
7
請輸入第二個數字(如果是除法,不能輸入0):
8
本次的計算結果為:56
+-------------------------------------------+
| + 選 1,- 選 2,* 選 3,/ 選 4,退出 選 0 |
+-------------------------------------------+
請輸入您的選擇:
0

2. 用JAVA編寫一個簡單的計算器,要求如下

太麻煩了 說個思路, 過去字元串後 先獲取+-*%的下標.然後然後分割,獲取到一個數組或list
然後循環獲取() 按照數學運算順序拼起來,
然後把公式拆分一步一步操作就得出結果啦

3. 用java實現一個簡單的計算器。

說實在的,你寫的這個計算器不怎麼樣。特別是布局。
我給你一個很簡單的吧。你自己學習一下。。

import java.awt.*;
import java.awt.event.*;
/**
*
* @author zzj
*
*/
public class Jisuanqi extends WindowAdapter {
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
TextField txt;
private Button[] b = new Button[17];
private String ss[] = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2",
"3", "*", "清空", "0", "=", "/", "關閉" };
static double a;
static String s, str;//定義變數 創建對像

public static void main(String args[]) {
(new Jisuanqi()).frame();
}

public void frame() {
Frame fm = new Frame("簡單計算器");
for (int i = 0; i <= 16; i++) {
b[i] = new Button(ss[i]);
}
for (int i = 0; i <= 15; i++) {
p2.add(b[i]);
} //創建按鈕 並添加到P2
b[16].setBackground(Color.yellow);
txt = new TextField(15);
txt.setEditable(false);
for (int i = 0; i <= 16; i++) {
b[i].addActionListener(new buttonlistener());//添加監聽器
}
b[16].addActionListener(new close());
fm.addWindowListener(this);
fm.setBackground(Color.red);
p1.setLayout(new BorderLayout());
p1.add(txt, "North");
p2.setLayout(new GridLayout(4, 4));
p3.setLayout(new BorderLayout());
p3.add(b[16]);
fm.add(p1, "North");
fm.add(p2, "Center");
fm.add(p3, "South");
fm.pack();
fm.setVisible(true);//都是些窗中設置 添加相關組件和監聽器
}

public void windowClosing(WindowEvent e) {
System.exit(0);//退出系統
}

class buttonlistener implements ActionListener {//編寫監聽器事件 通過按鍵得出給果
public void actionPerformed(ActionEvent e) {
Button btn = (Button) e.getSource();
if (btn.getLabel() == "=") {
jisuan();
str = String.valueOf(a);
txt.setText(str);
s = "";
} else if (btn.getLabel() == "+") {
jisuan();
txt.setText("");
s = "+";
} else if (btn.getLabel() == "-") {
jisuan();
txt.setText("");
s = "-";
} else if (btn.getLabel() == "/") {
jisuan();
txt.setText("");
s = "/";

} else if (btn.getLabel() == "*") {
jisuan();
txt.setText("");
s = "*";
} else {
txt.setText(txt.getText() + btn.getLabel());

if (btn.getLabel() == "清空")
txt.setText("");
}
}

public void jisuan() {//編寫具體計算方法
if (s == "+")
a += Double.parseDouble(txt.getText());
else if (s == "-")
a -= Double.parseDouble(txt.getText());
else if (s == "*")
a *= Double.parseDouble(txt.getText());
else if (s == "/")
a /= Double.parseDouble(txt.getText());
else
a = Double.parseDouble(txt.getText());
}
}
}

class close implements ActionListener {//退出
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}

4. 你好,怎樣簡單的用JAVA製作計算器

網上有很多代碼啊,你可以很容易就搜到的。

5. 用Java設計一個簡單的計算器。

無聊寫了個,修復了下Bug:

importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JTextField;

{

=1L;

privateJButtonplus,rece,multiply,divice,reset;
privateJTextFieldone,two,result;
privatebooleandevice_falg=false;

privatefinalintwidth=400,height=300;

publicCalculate(){
super("修改密碼");
this.setLayout(null);
this.setSize(width,height);
init();
Layout();
}

publicvoidinit(){
plus=newJButton("加");
rece=newJButton("減");
multiply=newJButton("乘");
divice=newJButton("除");
reset=newJButton("清空");
one=newJTextField();
two=newJTextField();
result=newJTextField();
}

publicvoidLayout(){
this.add(newJLabel("第一個數")).setBounds(20,10,60,80);
this.add(one).setBounds(100,38,100,25);
this.add(newJLabel("第二個數")).setBounds(20,40,60,80);
this.add(two).setBounds(100,70,100,25);
this.add(newJLabel("結果")).setBounds(20,85,60,80);
this.add(result).setBounds(100,110,100,25);

this.add(plus).setBounds(70,170,80,25);
this.add(rece).setBounds(200,170,80,25);
this.add(multiply).setBounds(70,200,80,25);
this.add(divice).setBounds(200,200,80,25);

this.add(reset).setBounds(300,220,80,25);

plus.addActionListener(this);
rece.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);

this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

publicbooleanFormat(){
booleanFLAG=false;
booleanflag=false;
Stringone=this.one.getText().toString().trim();
Stringtwo=this.two.getText().toString().trim();

if(one==null||one.equals("")||two==null||two.equals("")){
JOptionPane.showMessageDialog(getParent(),"請輸入完整信息!");
FLAG=false;
flag=true;
}

booleanboll_1=one.matches("[\d]{1,100}");
booleanboll_2=two.matches("[\d]{1,100}");
booleanboll_3=one.matches("[\d]{1,100}+[.]+[\d]{1,100}");
booleanboll_4=two.matches("[\d]{1,100}+[.]+[\d]{1,100}");
if(flag){
returnfalse;
}
if((boll_1&&boll_2)||(boll_3&&boll_4)||(boll_1&&boll_4)
||(boll_3&&boll_2)){
FLAG=true;
}else{
JOptionPane.showMessageDialog(getParent(),"請輸入數字!");
FLAG=false;
}

if(FLAG&&device_falg){
if(Double.parseDouble(two)==0){
JOptionPane.showMessageDialog(getParent(),"被除數不能為0!");
FLAG=false;
device_falg=false;
}
}

returnFLAG;
}

publicdoublePlus(doubleone,doubletwo){
returnone+two;
}

publicdoubleMultiply(doubleone,doubletwo){
returnone*two;
}

publicdoubleDivice(doubleone,doubletwo){
returnone/two;
}

publicdoubleRece(doubleone,doubletwo){
returnone-two;
}

publicvoidClear(){
one.setText("");
two.setText("");
result.setText("");
}

@Override
publicvoidactionPerformed(ActionEvente){
Objecto=e.getSource();
if(o==reset){
Clear();
return;
}
if(o==divice){
device_falg=true;
}
if(!Format()){
return;
}
doubleone=Double.parseDouble(this.one.getText());
doubletwo=Double.parseDouble(this.two.getText());
doubleresult=0;
if(o==plus){
result=Plus(one,two);
}elseif(o==rece){
result=Rece(one,two);
}elseif(o==multiply){
result=Multiply(one,two);
}elseif(o==divice){
result=Divice(one,two);
}
this.result.setText(""+result);
}
publicstaticvoidmain(String[]args){
newCalculate();
}
}

6. 用java編寫一個簡單計算器

/*

* @(#)JCalculator.java 1.00 06/17/2015

*/

importjava.awt.*;

importjava.awt.event.*;

importjavax.swing.*;

/**

* A simple calculator program.

*<p>I saw this program in a QQ group, and help a friend correct it.</p>

*

*@authorSingyuenYip

*@version1.00 12/29/2009

*@seeJFrame

*@seeActionListener

*/

{

/**

* Serial Version UID

*/

= -169068472193786457L;

/**

* This class help close the Window.

*@authorSingyuenYip

*

*/

{

publicvoidwindowClosing(WindowEvent we) {

System.exit(0);

}

}

inti;

// Strings for Digit & Operator buttons.

privatefinalString[]str= {"7","8","9","/","4","5","6","*","1",

"2","3","-",".","0","=","+"};

// Build buttons.

JButton[]buttons=newJButton[str.length];

// For cancel or reset.

JButtonreset=newJButton("CE");

// Build the text field to show the result.

JTextFielddisplay=newJTextField("0");

/**

* Constructor without parameters.

*/

publicJCalculator() {

super("Calculator");

// Add a panel.

JPanel panel1 =newJPanel(newGridLayout(4, 4));

// panel1.setLayout(new GridLayout(4,4));

for(i= 0;i<str.length;i++) {

buttons[i] =newJButton(str[i]);

panel1.add(buttons[i]);

}

JPanel panel2 =newJPanel(newBorderLayout());

// panel2.setLayout(new BorderLayout());

panel2.add("Center",display);

panel2.add("East",reset);

// JPanel panel3 = new Panel();

getContentPane().setLayout(newBorderLayout());

getContentPane().add("North", panel2);

getContentPane().add("Center", panel1);

// Add action listener for each digit & operator button.

for(i= 0;i<str.length;i++)

buttons[i].addActionListener(this);

// Add listener for "reset" button.

reset.addActionListener(this);

// Add listener for "display" button.

display.addActionListener(this);

// The "close" button "X".

addWindowListener(newWindowCloser());

// Initialize the window size.

setSize(800, 800);

// Show the window.

// show(); Using show() while JDK version is below 1.5.

setVisible(true);

// Fit the certain size.

pack();

}

publicvoidactionPerformed(ActionEvent e) {

Object target = e.getSource();

String label = e.getActionCommand();

if(target ==reset)

handleReset();

elseif("0123456789.".indexOf(label) > 0)

handleNumber(label);

else

handleOperator(label);

}

// Is the first digit pressed?

booleanisFirstDigit=true;

/**

* Number handling.

*@paramkey the key of the button.

*/

publicvoidhandleNumber(String key) {

if(isFirstDigit)

display.setText(key);

elseif((key.equals(".")) && (display.getText().indexOf(".") < 0))

display.setText(display.getText() +".");

elseif(!key.equals("."))

display.setText(display.getText() + key);

isFirstDigit=false;

}

/**

* Reset the calculator.

*/

publicvoidhandleReset() {

display.setText("0");

isFirstDigit=true;

operator="=";

}

doublenumber= 0.0;

Stringoperator="=";

/**

* Handling the operation.

*@paramkey pressed operator's key.

*/

publicvoidhandleOperator(String key) {

if(operator.equals("+"))

number+= Double.valueOf(display.getText());

elseif(operator.equals("-"))

number-= Double.valueOf(display.getText());

elseif(operator.equals("*"))

number*= Double.valueOf(display.getText());

elseif(operator.equals("/"))

number/= Double.valueOf(display.getText());

elseif(operator.equals("="))

number= Double.valueOf(display.getText());

display.setText(String.valueOf(number));

operator= key;

isFirstDigit=true;

}

publicstaticvoidmain(String[] args) {

newJCalculator();

}

}


運行界面:

7. 用Java做一個簡單的計算器

  1. 窗體
    package Calc;

    import java.awt.*;
    import java.awt.event.*;

    import javax.swing.*;

    /**
    *
    * 計算器程序
    *
    */
    public class CalcFrame extends JFrame {
    JButton[] buttons = new JButton[16];// 16個按鈕

    StringBuffer sb = null;//

    JTextField text1 = null;// 計算器結果顯示框

    String no1 = null;

    String sign = null;// 表示+-*/符號

    String[] s = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-",
    "*", "/", "=", "C" };// 面板上的字元

    public CalcFrame() {
    setTitle("計算器");
    setResizable(false);
    setBounds(200, 200, 300, 350);
    setLayout(null);

    sb = new StringBuffer();
    text1 = new JTextField();
    text1.setBounds(10, 10, 250, 30);// 設置位置
    text1.setFont(new Font("Arial", Font.PLAIN, 20));// 設置字體
    text1.setForeground(Color.RED);// 設置顏色
    add(text1);
    for (int i = 0; i < s.length; i++) {

    buttons[i] = new JButton(s[i]);
    buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
    add(buttons[i]);
    }// 生成面板上的按鈕.

    buttons[0].setBounds(10, 50, 50, 40);
    buttons[0].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(0);
    text1.setText(sb.toString());
    }

    });
    buttons[1].setBounds(70, 50, 50, 40);
    buttons[1].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(1);
    text1.setText(sb.toString());
    }

    });
    buttons[2].setBounds(130, 50, 50, 40);
    buttons[2].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(2);
    text1.setText(sb.toString());
    }

    });
    buttons[3].setBounds(190, 50, 50, 40);
    buttons[3].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(3);
    text1.setText(sb.toString());
    }

    });
    buttons[4].setBounds(10, 100, 50, 40);
    buttons[4].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(4);
    text1.setText(sb.toString());
    }

    });
    buttons[5].setBounds(70, 100, 50, 40);
    buttons[5].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(5);
    text1.setText(sb.toString());
    }

    });
    buttons[6].setBounds(130, 100, 50, 40);
    buttons[6].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(6);
    text1.setText(sb.toString());
    }

    });
    buttons[7].setBounds(190, 100, 50, 40);
    buttons[7].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(7);
    text1.setText(sb.toString());
    }

    });
    buttons[8].setBounds(10, 150, 50, 40);
    buttons[8].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(8);
    text1.setText(sb.toString());
    }

    });
    buttons[9].setBounds(70, 150, 50, 40);
    buttons[9].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.append(9);
    text1.setText(sb.toString());
    }

    });
    buttons[10].setBounds(130, 150, 50, 40);
    buttons[10].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "+";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[11].setBounds(190, 150, 50, 40);
    buttons[11].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "-";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[12].setBounds(10, 200, 50, 40);
    buttons[12].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "*";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[13].setBounds(70, 200, 50, 40);
    buttons[13].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sign = "/";
    no1 = text1.getText();
    sb.delete(0, sb.capacity());

    }
    });
    buttons[14].setForeground(Color.RED);
    buttons[14].setBounds(130, 200, 50, 40);
    buttons[14].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    int sum = 0;//最終結果
    if (sign.equals("+")) {
    int no2 = Integer.parseInt(no1);//取得前一個數

    int no3 = Integer.parseInt(text1.getText());//取得現在的數

    sum = no2 + no3;//累加

    text1.setText(String.valueOf(sum));

    }
    if (sign.equals("-")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 - no3;

    text1.setText(String.valueOf(sum));

    }
    if (sign.equals("*")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 * no3;

    text1.setText(String.valueOf(sum));

    }

    if (sign.equals("/")) {
    int no2 = Integer.parseInt(no1);

    int no3 = Integer.parseInt(text1.getText());

    sum = no2 / no3;

    text1.setText(String.valueOf(sum));

    }

    }

    });
    buttons[15].setBounds(190, 200, 50, 40);
    buttons[15].addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
    sb.delete(0, sb.capacity());//清除sb的內容
    text1.setText("");//結果框設置為空
    }
    });

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//響應關閉窗口
    setVisible(true);//顯示窗口
    }
    }

    2.主程序類
    package Calc;

    public class CalcTest {

    public static void main(String[] args) {
    CalcFrame f = new CalcFrame();

    }

    }



學習Java就到IT學習聯盟

8. 怎麼用java做個簡單的計算器

package com.gjq.test;

import java.util.Scanner;

public class xte {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("****************計算器****************");

System.out.print("請輸入數字①:");
Scanner scanner1 = new Scanner(System.in);
double num1= scanner1.nextDouble();

System.out.print("請輸入運算符,如:+ - * /:");
Scanner scanner2 = new Scanner(System.in);
String zifu= scanner2.next();

System.out.print("請輸入數字②:");
Scanner scanner3 = new Scanner(System.in);
double num3= scanner3.nextDouble();

char charzf =zifu.toCharArray()[0];
switch (charzf) {
case '+':
System.out.println("結果為:"+num1+" "+charzf+" "+num3+" = "+(num1+num3));
break;
case '-':
System.out.println("結果為:"+num1+" "+charzf+" "+num3+" = "+(num1-num3));
break;
case '*':
System.out.println("結果為:"+num1+" "+charzf+" "+num3+" = "+(num1*num3));
break;
case '/':
if(num3!=0){
System.out.println("結果為:"+num1+" "+charzf+" "+num3+" = "+(num1/num3));
}
break;
default:
System.out.println("輸入錯誤!");
break;
}

}

}

熱點內容
安卓手機微信語音怎麼不能轉文 發布:2025-02-09 08:25:30 瀏覽:921
c上機編程題 發布:2025-02-09 08:17:18 瀏覽:318
顯示語法錯誤編譯不出來 發布:2025-02-09 08:17:09 瀏覽:284
酒店配置什麼滅火系統 發布:2025-02-09 08:06:37 瀏覽:773
java至尊 發布:2025-02-09 08:03:23 瀏覽:558
pythonwith 發布:2025-02-09 08:00:25 瀏覽:172
Ftp打開文件是只讀模式 發布:2025-02-09 07:40:55 瀏覽:504
androidlistview點擊事件 發布:2025-02-09 07:25:52 瀏覽:171
targz解壓縮 發布:2025-02-09 06:59:19 瀏覽:311
wpsphp 發布:2025-02-09 06:58:41 瀏覽:962