學(xué)java的時(shí)候自己編的,很簡單,能夠連續(xù)輸入計(jì)算式后進(jìn)行計(jì)算
創(chuàng)新互聯(lián)建站是一家專注網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷策劃、微信平臺(tái)小程序開發(fā)、電子商務(wù)建設(shè)、網(wǎng)絡(luò)推廣、移動(dòng)互聯(lián)開發(fā)、研究、服務(wù)為一體的技術(shù)型公司。公司成立10余年以來,已經(jīng)為上千多家成都履帶攪拌車各業(yè)的企業(yè)公司提供互聯(lián)網(wǎng)服務(wù)?,F(xiàn)在,服務(wù)的上千多家客戶與我們一路同行,見證我們的成長;未來,我們一起分享成功的喜悅。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**簡易計(jì)算器,能夠進(jìn)行簡單的計(jì)算
*
* @see 2008.12.9
*/
public class CalculatorA
implements ActionListener{
private JFrame frame;
private JTextField field;
private JButton[] allButtons;
private JButton clearButton;
// private JButton backButton;
String result="";//保存結(jié)果
StringBuilder sb = new StringBuilder();//保存要進(jìn)行的計(jì)算式
int x = 0; //用來判斷上一次的事件類型
String str = "123+456-789*0.=/";
ArrayListString arrayList = new ArrayListString();//保存計(jì)算式,通過方法進(jìn)行運(yùn)算
public CalculatorA(){
frame = new JFrame("我的計(jì)算器v1.1");
frame.setLocation(300,300);
field = new JTextField(25);
allButtons = new JButton[16];
for(int i=0;iallButtons.length;i++){
allButtons[i]= new JButton(str.substring(i,i+1));
}
clearButton = new JButton("CLEAR");
// backButton = new JButton("——");
init();
setFondAndColor();
addEventHander();
}
public void init(){
frame.setLayout(new BorderLayout());
JPanel northPanel = new JPanel();
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
northPanel.setLayout(new FlowLayout());
centerPanel.setLayout(new GridLayout(4,4));
southPanel.setLayout(new FlowLayout());
northPanel.add(field);
for(int i=0;iallButtons.length;i++){
centerPanel.add(allButtons[i]);
}
southPanel.add(clearButton);
//southPanel.add(backButton);
frame.add(northPanel,BorderLayout.NORTH);
frame.add(centerPanel,BorderLayout.CENTER);
frame.add(southPanel,BorderLayout.SOUTH);
}
//設(shè)置輸入字體
public void setFondAndColor(){
field.setFont(new Font("宋體",Font.BOLD,24));
field.setBackground(new Color(100,200,200));
field.setForeground(Color.RED);
//設(shè)置字體從右起始
field.setHorizontalAlignment(JTextField.RIGHT);
}
public void showMi(){
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addEventHander(){
for(int i=0;iallButtons.length;i++){
allButtons[i].addActionListener(this);
}
clearButton.addActionListener(this);
// backButton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();//取得當(dāng)前事件返回的值
if("0123456789.".indexOf(str)!=-1){
if(x == 0){ //當(dāng)x為0時(shí)表示還沒有進(jìn)行輸入
result=str;
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 1){
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 2){
sb.delete(0,sb.length());
result = result+str;
sb.append(str);
field.setText(result);
x = 1;
}
else if(x == 3){
result = str;
sb.delete(0,sb.length());
arrayList.clear();
field.setText(str);
sb.append(str);
field.setText(str);
x = 1;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
result = str;
sb.append(str);
field.setText(str);
x = 1;
}
else{
result = result +str;
sb.append(str);
field.setText(result);
x = 1;
}
}
else if("+*-/".indexOf(str)!=-1){
if(x == 0){
field.setText("");
x = 2;
}
else if(x == 1){
result = result + str;
arrayList.add(sb.toString());
arrayList.add(str);
sb.append(str);
field.setText(result);
x = 2;
}
else if(x == 2){
x = 2;
}
else if(x == 3){
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 2;
}
else{
field.setText(result+str);
arrayList.add(result);
arrayList.add(str);
result = result+str;
x = 2;
}
}
else if("=".equals(str)){
if(x == 0){
field.setText("0");
arrayList.clear();
result = "0";
x = 3;
}
else if(x == 1){
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
else if(x == 2){
field.setText("數(shù)據(jù)格式錯(cuò)誤.....");
arrayList.clear();
x = 0;
}
else if(x == 3){
field.setText(result);
x = 3;
}
else if(x == 4){
result ="";
sb.delete(0,sb.length());
arrayList.clear();
x = 3;
}
else {
try{
arrayList.add(sb.toString());
arrayList = getResult(arrayList);
result = arrayList.get(0);
field.setText(result);
arrayList.clear();
x = 3;
}catch(Exception e1){
field.setText("數(shù)據(jù)格式異常");
x = 0;
}
}
}
else if("CLEAR".equals(str)){
arrayList.clear();
field.setText("0");
arrayList.add("0");
x = 4;
}
else{
if(result.length()1){
result = result.substring(0,result.length()-1);
if(sb.length()0){
sb.delete(sb.length()-1,sb.length());
}
else {
sb.delete(0,1);
}
field.setText(result);
x = 5;
}
else{
result = "";
sb.delete(0,sb.length());
arrayList.clear();
field.setText("0");
x = 0;
}
}
}
public static ArrayListString getResult(ArrayListString list){
String res = null;
String[] s = {"/","*","-","+"};
int i=0;
if(list.size()1){
for(;is.length;){
if(s[i].equals("/")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))/Double.parseDouble(list.get(j+1)));
//本地的數(shù)據(jù)格式
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("*")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))*Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else if(s[i].equals("-")){
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))-Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getNumberInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
else {
for(int j=0;jlist.size();j++){
if(list.get(j).equals(s[i])){
res = Double.toString(Double.parseDouble(list.get(j-1))+Double.parseDouble(list.get(j+1)));
NumberFormat nf = NumberFormat.getInstance();
res = nf.format(Double.parseDouble(res));
res = getChange(res);
list.set(j-1,res);
list.remove(j);
list.remove(j);
getResult(list);
}
}
i++;
}
}
}
return list;
}
//對數(shù)字字符串進(jìn)行排除不必要符號(hào)
public static String getChange(String res){
String s_temp = "";
char[] c = new char[res.length()];
for(int k=0;kc.length;k++){
c[k] = res.charAt(k);
}
for(int k=0;kc.length;k++){
if((c[k]= '0' c[k]= '9')|| c[k] == '.'){
s_temp += c[k];
}
}
return s_temp;
}
public static void main(String[] args){
new CalculatorA().showMi();
}
}
public static void main(String[] args) {
String st = "";
計(jì)算器 j = new 計(jì)算器();
boolean t = true;
while (t) {
System.out.print("請輸入計(jì)算代碼:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
st = br.readLine();
} catch (IOException ex) {
Logger.getLogger(計(jì)算器.class.getName()).log(Level.SEVERE, null, ex);
}
if (st.equals("end")) {
t = false;
} else if (!st.equals("")) {
j.處理(st);
}
}
}
public void 處理(String st) {
if (st.indexOf("+") != -1) {
加(符號(hào)處理(st, "+"));
} else if (st.indexOf("-") != -1) {
減(符號(hào)處理(st, "-"));
} else if (st.indexOf("*") != -1) {
乘(符號(hào)處理(st, "*"));
} else if (st.indexOf("/") != -1) {
除(符號(hào)處理(st, "/"));
}
}
public int[] 符號(hào)處理(String st, String s) {
int[] i = new int[2];
i[0] = Integer.parseInt(st.substring(0, st.indexOf(s)));
i[1] = Integer.parseInt(st.substring(st.indexOf(s) + 1));
return i;
}
public void 加(int x[]) {
System.out.println(x[0] + "+" + x[1] + "=" + (x[0] + x[1]));
}
public void 減(int[] x) {
System.out.println(x[0] + "-" + x[1] + "=" + (x[0] - x[1]));
}
public void 乘(int[] x) {
System.out.println(x[0] + "*" + x[1] + "=" + x[0] * x[1]);
}
public void 除(int x[]) {
if (x[1] == 0) {
System.out.print("除數(shù)不能為零");
return;
}
System.out.println(x[0] + "/" + x[1] + "=" + x[0] / x[1]);
}
可以運(yùn)行:輸入示例:55+62
以前寫的,給你了
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
//計(jì)算器面板
private JFrame f = new JFrame("Calculator");
//輸入面扳
private JPanel inputPanel = new JPanel();
//加減乘除面板
private JPanel operationPanel = new JPanel();
//數(shù)字面板
private JPanel buttonsPanel = new JPanel();
//輸入數(shù)據(jù)文本框
private JTextField input = new JTextField(20);
//退格鍵
private JButton backspace = new JButton("BackSpace");
//清空
private JButton CE = new JButton("CE ");
//刪除
private JButton C = new JButton("C ");
//四則運(yùn)算符號(hào)鍵
private JButton add = new JButton("+");
private JButton sub = new JButton("-");
private JButton mul = new JButton("*");
private JButton div = new JButton("/");
//小數(shù)點(diǎn)
private JButton decimal = new JButton(".");
//等號(hào)
private JButton equal = new JButton("=");
//數(shù)字鍵
private JButton zero = new JButton("0");
private JButton one = new JButton("1");
private JButton two = new JButton("2");
private JButton three = new JButton("3");
private JButton four = new JButton("4");
private JButton five = new JButton("5");
private JButton six = new JButton("6");
private JButton seven = new JButton("7");
private JButton eight = new JButton("8");
private JButton nine = new JButton("9");
private String num1 = "";//保存第一個(gè)運(yùn)算數(shù)字
private String operator = "";//保存運(yùn)算符號(hào)
public static void main(String[] args) {
new Calculator();//new計(jì)算器實(shí)例
}
public Calculator(){
//添加組件,布局
inputPanel.add(input);
f.add(inputPanel, BorderLayout.NORTH);
operationPanel.add(backspace);
operationPanel.add(CE);
operationPanel.add(C);
f.add(operationPanel, BorderLayout.CENTER);
buttonsPanel.add(add);
buttonsPanel.add(sub);
buttonsPanel.add(mul);
buttonsPanel.add(div);
buttonsPanel.add(one);
buttonsPanel.add(two);
buttonsPanel.add(three);
buttonsPanel.add(zero);
buttonsPanel.add(four);
buttonsPanel.add(five);
buttonsPanel.add(six);
buttonsPanel.add(decimal);
buttonsPanel.add(seven);
buttonsPanel.add(eight);
buttonsPanel.add(nine);
buttonsPanel.add(equal);
buttonsPanel.setLayout(new GridLayout(4, 4));
f.add(buttonsPanel, BorderLayout.SOUTH);
//注冊各個(gè)組件監(jiān)聽事件
backspace.addMouseListener(new OperationMouseListener());
CE.addMouseListener(new OperationMouseListener());
C.addMouseListener(new OperationMouseListener());
decimal.addMouseListener(new OperationMouseListener());
equal.addMouseListener(new OperationMouseListener());
//注冊四則運(yùn)算監(jiān)聽
add.addMouseListener(new CalcMouseListener());
sub.addMouseListener(new CalcMouseListener());
mul.addMouseListener(new CalcMouseListener());
div.addMouseListener(new CalcMouseListener());
//注冊數(shù)字監(jiān)聽事件
zero.addMouseListener(new NumberMouseListener());
one.addMouseListener(new NumberMouseListener());
two.addMouseListener(new NumberMouseListener());
three.addMouseListener(new NumberMouseListener());
four.addMouseListener(new NumberMouseListener());
five.addMouseListener(new NumberMouseListener());
six.addMouseListener(new NumberMouseListener());
seven.addMouseListener(new NumberMouseListener());
eight.addMouseListener(new NumberMouseListener());
nine.addMouseListener(new NumberMouseListener());
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class NumberMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(input.getText().trim().equals("0")){//如果文本框已經(jīng)是0,結(jié)果還是0
input.setText(((JButton)e.getSource()).getText().trim());
}else{//否則的話,把0添加到后面,譬如文本框是1,結(jié)果就為10
input.setText(input.getText().concat(((JButton)e.getSource()).getText().trim()));
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class CalcMouseListener implements MouseListener{
//如果輸入的是運(yùn)算符號(hào),保存第一個(gè)結(jié)果和運(yùn)算符號(hào)
public void mouseClicked(MouseEvent e) {
num1 = input.getText().trim();input.setText("");
operator = ((JButton)e.getSource()).getText().trim();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class OperationMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(e.getSource() == backspace){//退格鍵,刪除一個(gè)直到?jīng)]有字符刪除
String inputText = input.getText();
if(inputText.length() 0){
input.setText(inputText.substring(0, inputText.length() - 1));
}
}else if(e.getSource() == C){
input.setText("0");//C,清空所有運(yùn)算數(shù)字和符號(hào)
num1 = "";
}else if(e.getSource() == CE){
input.setText("0");//CE--將文本框置為0
}else if(e.getSource() == decimal){
String text = input.getText().trim();
//如果按了小數(shù)點(diǎn),如果文本框已經(jīng)有小數(shù)點(diǎn),不做任何操作,否則在結(jié)果后面加上小數(shù)點(diǎn)
if(text.indexOf(".") == -1){
input.setText(text.concat("."));
}
}else if(e.getSource() == equal){
//如果是等號(hào)
if(!operator.trim().equals("")){
if(!input.getText().trim().equals("")){
double result = 0D;
if(operator.equals("+")){//執(zhí)行加法運(yùn)算
result = Double.parseDouble(num1) + Double.parseDouble(input.getText().trim());
}else if(operator.equals("-")){//減法運(yùn)算
result = Double.parseDouble(num1) - Double.parseDouble(input.getText().trim());
}else if(operator.equals("*")){//乘法運(yùn)算
result = Double.parseDouble(num1) * Double.parseDouble(input.getText().trim());
}else if(operator.equals("/")){//除法運(yùn)算
result = Double.parseDouble(num1) / Double.parseDouble(input.getText().trim());
}
//格式化最終結(jié)果,保留兩位小數(shù)點(diǎn)
input.setText(new DecimalFormat("0.00").format(result));
}
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}
1加到50求和的Java代碼如下:
public?int?intSum(){
int?total?=?0;
for(int?i?=?1;i51;i?++){
total?+=?i;
}
System.out.println("1加到50結(jié)果為:"?+?total);
return?total;
}
結(jié)果是:1275
Java是一門面向?qū)ο缶幊陶Z言,不僅吸收了C++語言的各種優(yōu)點(diǎn),還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強(qiáng)大和簡單易用兩個(gè)特征。Java語言作為靜態(tài)面向?qū)ο缶幊陶Z言的代表,極好地實(shí)現(xiàn)了面向?qū)ο罄碚?,允許程序員以優(yōu)雅的思維方式進(jìn)行復(fù)雜的編程?[1]??。
Java具有簡單性、面向?qū)ο?、分布式、健壯性、安全性、平臺(tái)獨(dú)立與可移植性、多線程、動(dòng)態(tài)性等特點(diǎn)?[2]??。Java可以編寫桌面應(yīng)用程序、Web應(yīng)用程序、分布式系統(tǒng)和嵌入式系統(tǒng)應(yīng)用程序等
寫了個(gè)簡單的,不知道是不是你想要的,里面的main方法作了一個(gè)簡單的測試。幾個(gè)變量我定義為類變量。 public class PubTest {
private float fvar1, fvar2;
private int ivar1;
public PubTest(float fval1, float fval2, int ival) {
fvar1 = fval1;
fvar2 = fval2;
ivar1 = ival;
}
public PubTest() {
fvar1 = fvar2 = 0.0f;
ivar1 = 0;
}
public float getFvar1() {
return fvar1;
}
public float getFvar2() {
return fvar2;
}
public int getIvar1() {
return ivar1;
}
public void sum() {
fvar2 += fvar1;
}
public static void main(String[] args) {
PubTest pubTest = new PubTest(3.0f, 5.0f, 1);
pubTest.sum();
System.out.println(pubTest.getFvar2());
}
}