導航:首頁 > 源碼編譯 > java演算法小程序

java演算法小程序

發布時間:2023-01-07 10:11:19

Ⅰ 用java製作一個小程序,計算兩個數的加減乘除,用Applet實現

下面兩個可以么,是我做實驗答辯時用到的!

import java.awt.*;//AWT核心包
import java.awt.event.*;//提供事件類和監聽器
public class Counter extends Frame implements ActionListener
{
TextField t=new TextField("");//文本框
Panel p1=new Panel();//new一個panel,用於存放數字鍵和符號鍵。
Panel p2=new Panel();//new一個panel,用於存放開方、平方、和清除鍵。
Button[] b=new Button[10];//實例化Button對象
Button bAdd=new Button("加");
Button bSub=new Button("減");
Button bMul=new Button("乘以");
Button bPoint=new Button(".");
Button bDiv=new Button("除以");
Button bEqual=new Button("等於");
Button bSqrt=new Button("開方");
Button bPow=new Button("平方");
Button bNull=new Button("清除");

String str1=""; //str1和str2存放兩個輸入的數
String str2="";
String operator=null; //存放加減乘除以及開平方的符號
boolean first=true; //檢驗輸入的是否為第一個數
int countOper=0; //累計輸入符號的個數,連加連減等操作中會用到
double result=0.0; //暫存結果
double num1=0.0,num2=0.0; //兩個輸入的數做運算時轉化為double存放
boolean error=false; //檢驗除數是否為0

//構造方法
public Counter()
{
Frame s=new Frame("計算器");//創建Frame

for(int i=0;i<10;i++)//利用for循環將數字鍵添加進p1中
{
b[i]=new Button(String.valueOf(i));
p1.add(b[i]);
b[i].setActionCommand("number");
b[i].setForeground(new Color(150,20,20));
b[i].addActionListener(this);//調用addActionListener()方法注冊事件監聽器
}
p1.add(bPoint);
bPoint.setActionCommand("number");
p1.add(bAdd); //數字鍵,符號鍵放置在panel的p1中
p1.add(bSub);
p1.add(bMul);
p1.add(bDiv);
p1.add(bEqual);
p2.add(bSqrt);//開方鍵,平方鍵,清除鍵放置在panel的p2中
p2.add(bPow);
p2.add(bNull);
bAdd.setActionCommand("oper");
bSub.setActionCommand("oper");
bMul.setActionCommand("oper");
bDiv.setActionCommand("oper");

bAdd.setForeground(Color.red);//為組鍵設計顏色
bSub.setForeground(Color.red);
bMul.setForeground(Color.red);
bDiv.setForeground(Color.red);
bPoint.setForeground(Color.black);
bEqual.setForeground(Color.red);
bSqrt.setForeground(Color.blue);
bPow.setForeground(Color.blue);
bNull.setForeground(Color.blue);

bAdd.addActionListener(this);//調用addActionListener()方法注冊事件監聽器
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bPoint.addActionListener(this);
bEqual.addActionListener(this);
bSqrt.addActionListener(this);
bPow.addActionListener(this);
bNull.addActionListener(this);

p1.setLayout(new GridLayout(4,4,5,5));//網格布局管理器,把容器根據行數和列數分成同樣大小的單元,
//每個單元可容納一個組件,並且此組件會填滿網格單元,不能控
//制其占據網格的大小。4、4為網格的行、列數。5、5為組建之間的
//間距
p2.setLayout(new FlowLayout());//用FlowLayout布局管理器將組建默認劇中排放,默認間隙為5個像素
add(t,"North"); //frame的north放置輸入框,panel放置在center和south
add(p1,"Center");//將p1添加到Center中
add(p2,"South");//將p2添加到South中
setLocation(400,200);//設計按鈕尺寸
setSize(200,200);//設計窗口尺寸
setBackground(new Color(20,200,10));//設置Frame的背景,默認為白色
setVisible(true);//設置Frame設置為可見

addWindowListener(new WindowAdapter(){ //關閉窗口功能
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

//實現介面ActionListener
public void actionPerformed(ActionEvent e)
{
Button temp=(Button)e.getSource();

if(e.getActionCommand().equals("number"))
{
if(first)
{
str1=str1+temp.getLabel();
t.setText(str1);//將輸入的str1顯示在文本框中
}
else
{
str2=str2+temp.getLabel();
t.setText(str2);//將輸入的str2顯示在文本框中
}
}

else if(e.getActionCommand().equals("oper"))
{
if(str1=="") //如果還沒有輸入數就點擊運算符執行if
{
countOper=0;//若此,則將計數清零
first=true;
}
else
{
countOper++;//計算輸入符號的個數
if(countOper>1)//若輸入的符號個數多餘一個,則可以進行計算
{
getResult();
}
operator=temp.getLabel();//存放加減乘除以及開方、平方的符號
first=false;
}
}

else if(e.getActionCommand().equals("開方"))
{
double d=Math.sqrt(Double.parseDouble(str1));
str1=String.valueOf(d);//將計算出來的結果再次傳給str1,為連計算準備
t.setText(String.valueOf(d));//將計算出來的結果傳至文本框中
first=false;//置為false,即已輸入第一個數
}

else if(e.getActionCommand().equals("平方"))
{
double f=Math.pow(Double.parseDouble(str1),2);
str1=String.valueOf(f);
t.setText(String.valueOf(f));
first=false;
}

else if(e.getActionCommand().equals("清除"))
{
str1="";//清空
str2="";
t.setText("");//將文本框清空
countOper=0;//將按鍵計數器清零
first=true;
error=false;
}
else if(e.getActionCommand().equals("等於"))
{
if((str1=="")||(str2=="")) //兩個數沒有輸全就點擊等號,執行if
{
countOper=0;//將按鍵計數器清零
first=true;
}
else
{
getResult();
countOper=0;
}
}
}

//運算結果的方法
public void getResult()
{
num1=Double.parseDouble(str1);
num2=Double.parseDouble(str2);

if(operator.equals("加"))
{
result=num1+num2;
}

else if(operator.equals("減"))
{
result=num1-num2;
}

else if(operator.equals("乘以"))
{
result=num1*num2;
}

else if(operator.equals("除以"))
{
if(num2==0.0) //除數為0的處理方法
{
error=true;
}
else
{
result=num1/num2;
}
}

if(error)
{
t.setText("error");
}
else
{
t.setText(String.valueOf(result));
str1=String.valueOf(result); //運算後把結果放入str1中,str2清空,為連加連減等操作做准備
str2="";
}
}

//主方法
public static void main(String[] args)
{
new Counter();//創建一個對象"計算器"
}
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CalculatorPanel extends JPanel
implements ActionListener
{ public CalculatorPanel()
{ setLayout(new BorderLayout());

display = new JTextField("0");
display.setEditable(false);
add(display, "North");

JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4));
String buttons = "789/456*123-0.=+";
for (int i = 0; i < buttons.length(); i++)
addButton(p, buttons.substring(i, i + 1));
add(p, "Center");
}

private void addButton(Container c, String s)
{ JButton b = new JButton(s);
c.add(b);
b.addActionListener(this);
}

public void actionPerformed(ActionEvent evt)
{ String s = evt.getActionCommand();
if ('0' <= s.charAt(0) && s.charAt(0) <= '9'
|| s.equals("."))
{ if (start) display.setText(s);
else display.setText(display.getText() + s);
start = false;
}
else
{ if (start)
{ if (s.equals("-"))

else op = s;
}
else
{ calculate(Double.parseDouble(display.getText()));
op = s;
start = true;
}
}
}

public void calculate(double n)
{ if (op.equals("+")) arg += n;
else if (op.equals("-")) arg -= n;
else if (op.equals("*")) arg *= n;
else if (op.equals("/")) arg /= n;
else if (op.equals("=")) arg = n;
display.setText("" + arg);
}

private JTextField display;
private double arg = 0;
private String op = "=";
private boolean start = true;
}

public class CalculatorApplet extends JApplet
{ public void init()
{ Container contentPane = getContentPane();
contentPane.add(new CalculatorPanel());
}
}

Ⅱ JAVA作一個小程序

代碼如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ShortTest3 extends JFrame implements ActionListener {
JButton jb1;
TextArea ta;
JPanel j1;
JPanel j2;

public ShortTest3() {
Container contentPane = this.getContentPane();
j1 = new JPanel();
jb1 = new JButton("點擊計算原材料");
jb1.addActionListener(this);
j1.add(jb1);
ta = new TextArea();
j2 = new JPanel();
j2.add(ta);
contentPane.add(j1, "North");
contentPane.add(j2, "Center");
}

public static void main(String[] args) {
ShortTest3 m = new ShortTest3();
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m.setSize(500, 300);
m.setLocationRelativeTo(null);
m.setVisible(true);
}

public void actionPerformed(ActionEvent ae) {
while(true) {
int count = 0;
String tempStr = JOptionPane.showInputDialog(null, "請輸入保險絲需求量: ", "輸入", JOptionPane.QUESTION_MESSAGE);
if(tempStr == null) {
int var = JOptionPane.showConfirmDialog(null, "退出計算?", "退出", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(var == JOptionPane.YES_OPTION) break;
}
try{
count = Integer.parseInt(tempStr);
} catch(Exception e) {
continue;
}
ta.append("要做" + count + "個保險絲需要:" + count + "個熔絲+" + count*2 + "個銅帽+" + count + "個玻璃管");
ta.append("\n");
break;
}
}
}

Ⅲ 求只需要加減乘除功能的簡單的java計算器小程序!

package jisuanqi;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.*;

/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class Jisuan extends JFrame {
JPanel contentPane;
JButton btnmultiply = new JButton();
JButton btn3 = new JButton();
JButton btndivide = new JButton();
JButton btn2 = new JButton();
JButton btn5 = new JButton();
JButton btn0 = new JButton();
JButton btnclear = new JButton();
JButton btnequal = new JButton();
JButton btn1 = new JButton();
JButton btn6 = new JButton();
JButton bntplus = new JButton();
JButton btnminus = new JButton();
JButton btn4 = new JButton();
JButton btn9 = new JButton();
JButton btn8 = new JButton();
JButton btn7 = new JButton();
JPanel jPanel1 = new JPanel();
JTextField txt = new JTextField();
boolean flag=false;
String operand1;
String operand2;
double result;
String action;

public Jisuan() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}

/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(300, 400));
setTitle("Frame Title");
btnmultiply.setBounds(new Rectangle(227, 322, 42, 35));
btnmultiply.setText("+");
btnmultiply.addActionListener(new Jisuan_jButton1_actionAdapter(this));
contentPane.setBorder(BorderFactory.createEtchedBorder());
contentPane.setToolTipText("");
btn3.setBounds(new Rectangle(160, 263, 42, 35));
btn3.setText("3");
btn3.addActionListener(new Jisuan_btn3_actionAdapter(this));
btndivide.setBounds(new Rectangle(227, 263, 42, 35));
btndivide.setText("-");
btndivide.addActionListener(new Jisuan_jButton3_actionAdapter(this));
btn2.setBounds(new Rectangle(93, 263, 42, 35));
btn2.setText("2");
btn2.addActionListener(new Jisuan_btn2_actionAdapter(this));
btn5.setBounds(new Rectangle(93, 201, 42, 35));
btn5.setText("5");
btn5.addActionListener(new Jisuan_btn5_actionAdapter(this));
btn0.setBounds(new Rectangle(25, 322, 42, 35));
btn0.setText("0");
btn0.addActionListener(new Jisuan_btn0_actionAdapter(this));
btnclear.setBounds(new Rectangle(93, 322, 42, 35));
btnclear.setText("c");
btnclear.addActionListener(new Jisuan_jButton7_actionAdapter(this));
btnequal.setBounds(new Rectangle(160, 322, 42, 35));
btnequal.setText("=");
btnequal.addActionListener(new Jisuan_btnequal_actionAdapter(this));
btn1.setBounds(new Rectangle(25, 263, 42, 35));
btn1.setText("1");
btn1.addActionListener(new Jisuan_btn1_actionAdapter(this));
btn6.setBounds(new Rectangle(160, 201, 42, 35));
btn6.setText("6");
btn6.addActionListener(new Jisuan_btn6_actionAdapter(this));
bntplus.setBounds(new Rectangle(227, 201, 42, 35));
bntplus.setText("*");
bntplus.addActionListener(new Jisuan_btnminus_actionAdapter(this));
btnminus.setBounds(new Rectangle(227, 137, 42, 35));
btnminus.setText("/");
btnminus.addActionListener(new Jisuan_bntplus_actionAdapter(this));
btn4.setBounds(new Rectangle(25, 201, 42, 35));
btn4.setText("4");
btn4.addActionListener(new Jisuan_btn4_actionAdapter(this));
btn9.setBounds(new Rectangle(160, 137, 42, 35));
btn9.setText("9");
btn9.addActionListener(new Jisuan_btn9_actionAdapter(this));
btn8.setBounds(new Rectangle(93, 137, 42, 35));
btn8.setText("8");
btn8.addActionListener(new Jisuan_btn8_actionAdapter(this));
btn7.setBounds(new Rectangle(25, 137, 42, 35));
btn7.setText("7");
btn7.addActionListener(new Jisuan_btn7_actionAdapter(this));
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(13, 128, 270, 244));
txt.setHorizontalAlignment(SwingConstants.RIGHT);
txt.setBounds(new Rectangle(13, 61, 270, 46));
contentPane.add(btndivide);
contentPane.add(btn3);
contentPane.add(btn2);
contentPane.add(btnclear);
contentPane.add(btnmultiply, null);
contentPane.add(btnequal);
contentPane.add(btn1);
contentPane.add(btn0);
contentPane.add(btn5);
contentPane.add(btn6);
contentPane.add(bntplus);
contentPane.add(btn4);
contentPane.add(btn7);
contentPane.add(btn8);
contentPane.add(btn9);
contentPane.add(btnminus);
contentPane.add(jPanel1);
contentPane.add(txt);
}

public void jButton1_actionPerformed(ActionEvent e) {
action="plus";
operand1=txt.getText();
txt.setText("");
flag=true;
}

public void jButton3_actionPerformed(ActionEvent e) {
action="minus";
operand1=txt.getText();
txt.setText("");
flag=true;
}

public void btn1_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn1.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn1.getActionCommand());
}
}
public void btn6_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn6.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn6.getActionCommand());
}
}
public void btn2_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn2.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn2.getActionCommand());
}
}
public void btn3_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn3.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn3.getActionCommand());
}
}
public void btn4_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn4.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn4.getActionCommand());
}
}
public void btn5_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn5.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn5.getActionCommand());
}
}
public void btn7_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn7.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn7.getActionCommand());
}
}
public void btn8_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn8.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn8.getActionCommand());
}
}
public void btn9_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn9.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn9.getActionCommand());
}
}
public void btn0_actionPerformed(ActionEvent e) {
if(flag){
txt.setText(btn0.getActionCommand());
flag=false;
}
else{
txt.setText(txt.getText()+btn0.getActionCommand());
}
}

public void jButton7_actionPerformed(ActionEvent e) {
txt.setText("");
}

public void bntplus_actionPerformed(ActionEvent e) {
/*
operand1=Integer.parseInt(txt.getText());
action="plus";
flag=true;
*/
action="divide";
operand1=txt.getText();
txt.setText("");
flag=true;
}

public void btnminus_actionPerformed(ActionEvent e) {
action="multiply";
operand1=txt.getText();
txt.setText("");
flag=true;
}

public void btnequal_actionPerformed(ActionEvent e) {
double digit1;
double digit2;
operand2=txt.getText();
if(flag==false){
if(action.equals("divide")){
digit1=Integer.parseInt(operand1);
digit2=Integer.parseInt(operand2);
result=digit1 / digit2;
txt.setText(new Double(result).toString());
flag=true;
}else if(action.equals("plus")){
digit1=Integer.parseInt(operand1);
digit2=Integer.parseInt(operand2);
result=digit1 + digit2;
txt.setText(""+(int)result);
flag=true;
}else if(action.equals("multiply")){
digit1=Integer.parseInt(operand1);
digit2=Integer.parseInt(operand2);
result=digit1 * digit2;
txt.setText(""+(int)result);
flag=true;
}else if(action.equals("minus")){
digit1=Integer.parseInt(operand1);
digit2=Integer.parseInt(operand2);
result=digit1-digit2;
txt.setText(""+(int)result);
flag=true;
}
}
}

}

class Jisuan_btnminus_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btnminus_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btnminus_actionPerformed(e);
}
}

class Jisuan_bntplus_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_bntplus_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.bntplus_actionPerformed(e);
}
}

class Jisuan_jButton7_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_jButton7_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.jButton7_actionPerformed(e);
}
}

class Jisuan_btn0_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn0_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn0_actionPerformed(e);
}
}

class Jisuan_btn9_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn9_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn9_actionPerformed(e);
}
}

class Jisuan_btn8_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn8_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn8_actionPerformed(e);
}
}

class Jisuan_btn7_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn7_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn7_actionPerformed(e);
}
}

class Jisuan_btn6_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn6_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn6_actionPerformed(e);
}
}

class Jisuan_btn5_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn5_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn5_actionPerformed(e);
}
}

class Jisuan_btn4_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn4_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn4_actionPerformed(e);
}
}

class Jisuan_btn3_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn3_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn3_actionPerformed(e);
}
}

class Jisuan_btn2_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn2_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn2_actionPerformed(e);
}
}

class Jisuan_btn1_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btn1_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btn1_actionPerformed(e);
}
}

class Jisuan_jButton3_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_jButton3_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.jButton3_actionPerformed(e);
}
}

class Jisuan_jButton1_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_jButton1_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}

class Jisuan_btnequal_actionAdapter implements ActionListener {
private Jisuan adaptee;
Jisuan_btnequal_actionAdapter(Jisuan adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.btnequal_actionPerformed(e);
}
}
這個是實現的方法,按鈕的名字不一定一樣,最主要是這個要一樣 action="minus";

main方法 用JB他自己就生成啦

Ⅳ 一個JAVA小程序,計算器的

text.setEditable(false);// 得寫到方法體中去,單獨是不能存在的,你看來是寫得頭暈了哈
第二個類那樣是用不了text.setText();的
沒有這個對象,你把它們寫到同一個類中去就沒問題了。
非要這么寫,那你得再寫個方法將text對象傳遞出來在第二個類中獲取來使用……

你寫得有點兒亂,我也不知道怎麼改了!寫一個太花時間,我這邊給你一個吧!

你說按鈕距離那就是你布局沒有處理好!建議直接像下面給出的程序那樣!也簡單

出了問題了不怕,問題越多進步越快哈

有問題你可以加這個群進行提問:5358308,java world!(two)

給你一個計算器程序

//第一個類是GUI,兩個類放兩文件里去
import javax.swing.*;
import java.awt.Container;
import java.awt.event.*;

public class Calculate_GUI extends JFrame{
private JPanel p1;
private JButton keyButton[]=new JButton[16],signButton,clearButton,deleteButton;
private JTextField outputField;
private Container contentPane;
private boolean firstInput=true;
private Calculate_Model model=new Calculate_Model();

public Calculate_GUI(){
p1=new JPanel();
keyButton[0]=new JButton("1"); //創建各個按鈕
keyButton[1]=new JButton("2");
keyButton[2]=new JButton("3");
keyButton[3]=new JButton("/");
keyButton[4]=new JButton("4");
keyButton[5]=new JButton("5");
keyButton[6]=new JButton("6");
keyButton[7]=new JButton("*");
keyButton[8]=new JButton("7");
keyButton[9]=new JButton("8");
keyButton[10]=new JButton("9");
keyButton[11]=new JButton("-");
keyButton[12]=new JButton("0");
keyButton[13]=new JButton(".");
keyButton[14]=new JButton("=");
keyButton[15]=new JButton("+");
clearButton=new JButton("c");
signButton=new JButton("+/-");
deleteButton=new JButton("←");
outputField=new JTextField(); //它允許編輯單行文本
outputField.setText("0");
outputField.setEditable(false); //指示此 TextComponent 是否應該為可編輯的
contentPane=this.getContentPane(); //返回此窗體的 contentPane 對象;

this.setSize(250,250);
p1.setLayout(new java.awt.GridLayout(4,5)); //創建具有4行5列的布局

for(int i=0;i<keyButton.length;i++) //在容器中畫上按鈕
{
if(i==4) p1.add(deleteButton);
if(i==8) p1.add(clearButton);
if(i==12) p1.add(signButton);
keyButton[i].setFont(new java.awt.Font("Dialog",3,15));//設置字體Dialog字體名,樣式,大小
p1.add(keyButton[i]);
}

contentPane.add(outputField,java.awt.BorderLayout.NORTH);
contentPane.add(p1,java.awt.BorderLayout.CENTER);
this.show();
} //用於顯示界面

public void registEvent() //注冊各個事件
{
this.addWindowListener(new WindowAdapter() //窗口事件,窗口關閉里程序關閉
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});

for(int i=0;i<keyButton.length;i++)
{
keyButton[i].addActionListener(new keyButtonHandler()); //為每一個按鈕添加監聽器
}

signButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
outputField.setText(String.valueOf(model.toSign(Double.parseDouble(outputField.getText()))));
}
});

deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
outputField.setText(model.backSpace(outputField.getText()));
if(outputField.getText().equals("0"))
firstInput=true;
}
});

clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstInput=true;
outputField.setText("0");
model.reset();
}
});
}

class keyButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
char actionCommand=ae.getActionCommand().charAt(0);

switch(actionCommand)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '.':

if(firstInput) //是否為首次輸入
{
outputField.setText(String.valueOf(actionCommand));
firstInput=false;
}

else
outputField.setText(outputField.getText()+actionCommand);
break;

case '+':
case '-':
case '*':
case '/':

if(firstInput)
model.setOperate(actionCommand);
else
{
model.setOperateNumber(Double.parseDouble(outputField.getText()));
model.calculating();
model.setOperate(actionCommand);
outputField.setText(String.valueOf(model.getResult()));
firstInput=true;
}

break;

case '=':

if(firstInput)
{
model.calculating();
outputField.setText(String.valueOf(model.getResult()));
}
else
{
model.setOperateNumber(Double.parseDouble(outputField.getText()));
model.calculating();
outputField.setText(String.valueOf(model.getResult()));
firstInput=true;
}
}
}
}

public static void main(String args[])
{
new Calculate_GUI().registEvent();
}
}

/******************************************
*****計算的模塊****************************/
public class Calculate_Model
{
private double result;
private double operateNumber;
private char operate;

public Calculate_Model() //構造方法進行初始化
{
result=0; //結果
operateNumber=0; //操作數
operate=' '; //操作符
}

public void setResult(double n) //設置結果,成員變數result是private的
{
result=n;
}

public void setOperate(char o) //設置操作符
{
operate=o;
}

public void setOperateNumber(double n) //設置操作數
{
operateNumber=n;
}

public double getResult() //獲取結果
{
return result;
}

public void calculating() //計算過程
{
switch(operate)
{
case ' ':result=operateNumber;break; //分別對操作判斷後進行相應操作
case '+':result+=operateNumber;break;
case '-':result-=operateNumber;break;
case '*':result*=operateNumber;break;
case '/':result/=operateNumber;break;
}
}

public void reset() //重設方法
{
result=0;
operateNumber=0;
operate=' ';
}

public double toSign(double n) //正負轉化
{
return 0-(n-0);
}

public String backSpace(String n) //對backSpace設置
{
String reResult="0";
try
{
reResult=n.substring(0,n.length()-1); //從第一個開始取前n-1個
Double.parseDouble(reResult); //將其轉化為Double型
}
catch(NumberFormatException e)
{
reResult="0";
}

return reResult;
}

}

Ⅳ JAVA小程序編寫

1.JavaPow.java

import java.util.Scanner;

public class JavaPow {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入一個數求平方:");
double num = sc.nextDouble();
System.out.println(num + "的平方結果是:" + Math.pow(num, 2));
}
}

2.CompareTest.java

public class CompareTest {
public static void main(String[] args) {
int a = 10, b = 8;
if(a>b){
System.out.println("排序結果是:"+b+"\t"+a);
}else{
System.out.println("排序結果是:"+a+"\t"+b);
}
}
}

3.RateMoney.java

import java.util.Scanner;

public class RateMoney {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double money=0;
double rate=0;
System.out.print("請輸入匯款金額:");
money=sc.nextDouble();

if(money<0){
rate=0;
}
else if(money>0&&money<=100){
rate=1;
}else if(money>100&&money<=5000){
rate=money/100;
}else{
rate=50;
}
System.out.println("匯"+money+"元錢需匯款費:"+rate+"元");
}

}

三個都已經寫出來了..

你好好看看吧!!

祝你早日成功!

Ⅵ java:編寫一個計算器小程序,要求可以做加減乘除運算

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
private static final long serialVersionUID = 8199443193151152362L;
private JButton bto_s=new JButton("sqrt"),bto_zf=new JButton("+/-"),bto_ce=new JButton("CE"),bto_c=new JButton("C"),bto_7=new JButton("7"),
bto_8=new JButton("8"),bto_9=new JButton("9"),bto_chu=new JButton("/"),bto_4=new JButton("4"),bto_5=new JButton("5"),
bto_6=new JButton("6"),bto_cheng=new JButton("*"),bto_1=new JButton("1"),bto_2=new JButton("2"),bto_3=new JButton("3"),
bto_jian=new JButton("-"),bto_0=new JButton("0"),bto_dian=new JButton("."),bto_deng=new JButton("="),bto_jia=new JButton("+");
JButton button[]={bto_s,bto_zf,bto_ce,bto_c,bto_7,bto_8,bto_9,bto_chu,bto_4,bto_5,bto_6,bto_cheng,bto_1,bto_2,bto_3,bto_jian,
bto_0,bto_dian,bto_deng,bto_jia};
private JTextField text_double;// = new JTextField("0");
private String operator = "="; //當前運算的運算符
private boolean firstDigit = true; // 標志用戶按的是否是整個表達式的第一個數字,或者是運算符後的第一個數字
private double resultNum = 0.0; // 計算的中間結果
private boolean operateValidFlag = true; //判斷操作是否合法
public Calculator()
{
super("Calculator");
this.setBounds(300, 300, 300, 300);
this.setResizable(false);
this.setBackground(Color.orange);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());//設置布局
text_double=new JTextField("0",20);//設置文本區
text_double.setHorizontalAlignment(JTextField.RIGHT);//設置水平對齊方式未右對齊
this.getContentPane().add(text_double,BorderLayout.NORTH);//將文本區添加到Content北部
JPanel panel=new JPanel(new GridLayout(5,4));//在內容窗口添加一個網格布局
this.getContentPane().add(panel);//添加panel面板
for(int i=0;i<button.length;i++)//在面板上添加按鈕
panel.add(button[i]);

for(int i=0;i<button.length;i++)
button[i].addActionListener(this);//為按鈕注冊
text_double.setEditable(false);//文本框不可編輯
text_double.addActionListener(this);//

this.setVisible(true);
}
public void actionPerformed(ActionEvent e)//
{
String c= e.getActionCommand();//返回與此動作相關的命令字元串。
System.out.println("##########command is "+c);
if(c.equals("C")){
handleC(); //用戶按了「C」鍵
}
else if (c.equals("CE")) // 用戶按了"CE"鍵
{
text_double.setText("0");
}
else if ("0123456789.".indexOf(c) >= 0) // 用戶按了數字鍵或者小數點鍵
{
handleNumber(c); // handlezero(zero);
} else //用戶按了運算符鍵
{
handleOperator(c);
}
}
private void handleC() // 初始化計算器的各種值
{
text_double.setText("0");
firstDigit = true;
operator = "=";
}
private void handleNumber(String button) {
if (firstDigit)//輸入的第一個數字
{
text_double.setText(button);
} else if ((button.equals(".")) && (text_double.getText().indexOf(".") < 0))//輸入的是小數點,並且之前沒有小數點,則將小數點附在結果文本框的後面
//如果字元串參數作為一個子字元串在此對象中出現,則返回第一個這種子字元串的第一個字元的索引;如果它不作為一個子字元串出現,則返回 -1
{
text_double.setText(text_double.getText() + ".");
} else if (!button.equals("."))// 如果輸入的不是小數點,則將數字附在結果文本框的後面
{
text_double.setText(text_double.getText() + button);
}
// 以後輸入的肯定不是第一個數字了
firstDigit = false;
}
private void handleOperator(String button) {

if (operator.equals("/")) {
// 除法運算
// 如果當前結果文本框中的值等於0
if (getNumberFromText() == 0.0){
// 操作不合法
operateValidFlag = false;
text_double.setText("除數不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("+")){
// 加法運算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
// 減法運算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
// 乘法運算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根運算
if(getNumberFromText()<0){
operateValidFlag = false;
text_double.setText("被開方數不能為負數");}
else
resultNum = Math.sqrt(resultNum);
}
else if (operator.equals("+/-")){
// 正數負數運算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
// 賦值運算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
// 雙精度浮點數的運算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
text_double.setText(String.valueOf(t1));
} else {
text_double.setText(String.valueOf(resultNum));
}
}
operator = button; //運算符等於用戶按的按鈕
firstDigit = true;
operateValidFlag = true;
}
private double getNumberFromText() //從結果的文本框獲取數字
{
double result = 0;
try {
result = Double.valueOf(text_double.getText()).doubleValue(); // ValueOf()返回表示指定的 double 值的 Double 實例
} catch (NumberFormatException e){
}
return result;
}
public static void main(final String[] args) {
new Calculator();
}
}

Ⅶ 用JAVA編寫一個小程序,不限類型好玩點的。

控制台小游戲 class YZDEL { public static void main(String[] args) { java.util.Random Shiji = new java.util.Random(); java.util.Scanner Shuru = new java.util.Scanner(System.in); java.util.Scanner Nan = new java.util.Scanner(System.in); int YingxHP = 20; int YingxMP = 0; int MogHP = 20; int MogMP = 0; int MogDo = 0; int fangyu = 0; System.out.println("┏━━━━_┏━━┣┣┓_┓┏━┳━┳┓┓━┓"); System.out.println("┏┣━━━┓┏━━┣┣┓┃┏┃┃┓┃_"); System.out.println("┣┣━━━┫_━━┻__┃_┓┃┃_┏━┣━━┓"); System.out.println("┣┣━━━┫┏━━━━┓_━━┣━┛┗━┻━┻┛┃┃"); System.out.println("┏┣━━━┓┣━━━━┫┃┃┃┗__┃┃┣━_"); System.out.println("┛┗_┗━━━━_┗___━━┛┛┗━__━┛"); System.out.println(); System.out.println(" 作者:天狐空幻"); System.out.println(); System.out.println("說明:勇者的操作方式為以下所示:"); System.out.println(" 使用攻擊需消耗1MP 傷害1HP"); System.out.println(" 使用蓄力可增加1MP 傷害0HP"); System.out.println(" 使用躲閃需消耗0MP 傷害0HP 躲避攻擊"); System.out.println(" 使用重擊需消耗3MP 傷害2HP 防禦無效"); System.out.println(" 惡龍攻擊力高, 注意防禦是取勝的關鍵"); System.out.println(" 惡龍MP達到4時可能會放出火焰無法躲避"); System.out.println(" 准備說明完畢,那麼讓我們來挑戰惡龍吧!"); System.out.println("=================================="); //難度選擇 System.out.println("請選擇難度"); System.out.println("1.娛樂 2.挑戰 3.噩夢"); int ND = Nan.nextInt(); System.out.println("=================================="); while(true) { //HP,MP的顯示 System.out.print("勇者: "); System.out.print(" HP "); for(int x=YingxHP;x>0;x--) System.out.print("*"); System.out.print(" "+YingxHP); System.out.println(); System.out.print(" "); System.out.print(" MP "); for(int x=YingxMP;x>0;x--) System.out.print("*"); System.out.print(" "+YingxMP); System.out.println(); System.out.print("惡龍: "); System.out.print(" HP "); for(int y=MogHP;y>0;y--) System.out.print("*"); System.out.print(" "+MogHP); System.out.println(); System.out.print(" "); System.out.print(" MP "); for(int y=MogMP;y>0;y--) System.out.print("*"); System.out.print(" "+MogMP); System.out.println(); System.out.println("=================================="); //勝利判定 if(YingxHP<1) {System.out.println();System.out.println("勇者HP為0! 不..不可能..我怎麼會..勇者倒下了。再接再厲吧!~");System.out.println();break;} if(MogHP<1) {System.out.println();System.out.println("惡龍HP為0! 惡龍絕望的哀鳴中倒了下去。勇者勝利了。恭喜你挑戰成功!!");System.out.println();break;} //角色輸入判定 System.out.println("你要做什麼:"); System.out.println("1.攻擊 2.蓄力"); System.out.println("3.躲閃 4.重擊"); System.out.println("____________________"); int Do = Shuru.nextInt(); //敵人輸入判定 //娛樂難度 if(ND==1){ for(int i=1;i<3;i++) MogDo = Shiji.nextInt(4);} //挑戰難度 if(ND==2){ if(YingxMP==0&&MogMP==0) {MogDo = 0;} else if(MogMP==0){for(int i=1;i<3;i++) MogDo = Shiji.nextInt(2);} else if(YingxMP>2&&MogMP>2) MogDo = 2; else if(MogMP<4) {for(int i=1;i<4;i++) MogDo = Shiji.nextInt(3);} else MogDo = 3;} //噩夢難度 if(ND==3){ if(Do==1) MogDo=1; if(Do==2&&MogMP>0) MogDo=2; if(Do==2&&MogMP==0) MogDo=0; if(Do==3&&MogMP<4) MogDo=0; if(Do==3&&MogMP>=4) MogDo=3;}//變態判定。。 //戰斗分析 //防禦 if(Do==3) {fangyu=1;System.out.println("你靈巧的躲避攻擊!");} if(MogDo==1) {fangyu=1;System.out.println("惡龍進行防禦!");} //角色判定 if(Do==1&&YingxMP==0) {System.out.println("MP不足!");} if(Do==1&&YingxMP>0) { if(fangyu==0) {MogHP=MogHP-1;YingxMP=YingxMP-1;System.out.println("你發動攻擊!");} if(fangyu==1) {YingxMP=YingxMP-1;System.out.println("你的攻擊被格擋!");}} if(Do==2) {YingxMP=YingxMP+1;System.out.println("你進行蓄力!");} if(Do==4&&YingxMP<3) {System.out.println("MP不足!");} if(Do==4&&YingxMP>2) {MogHP=MogHP-2;YingxMP=YingxMP-3;System.out.println("你發動重擊!");} if(Do> 4) System.out.println("你不知所措..."); //敵人判定 if(MogDo==2&&MogMP==0) {System.out.println("惡龍在發呆!");} if(MogDo==2&&MogMP>0) { if(fangyu==0) {YingxHP=YingxHP-2;MogMP=MogMP-1;System.out.println("惡龍發動攻擊!");} if(fangyu==1) {MogMP=MogMP-1;System.out.println("惡龍的攻擊被躲開了!");}} if(MogDo==0) {MogMP=MogMP+1;System.out.println("惡龍進行蓄力!");} if(MogDo==3&&MogMP<4) {System.out.println("惡龍在發呆!");} if(MogDo==3&&MogMP>3) {YingxHP=YingxHP-4;MogMP=MogMP-4;System.out.println("惡龍發動火焰吐吸!躲避不能!");} //結束 fangyu = 0; MogDo = 0; System.out.println("____________________"); System.out.println(); System.out.println("=================================="); } } }

Ⅷ 緊急高分求助: 一個java演算法的小程序

package test;

public class Test {
public static void main(String[] args){
System.out.println(new Test().isValid(49927398716l));
}

public int isValid(long num){
int sum=0;
for(int i=1;i<12;i++){
if(i%2!=0)
sum+=num%10;
else{
long temp=num%10*2;
sum+=temp/10+temp%10;
}
num=num/10;
}
return sum%10==0?1:0;
}
}
isValid方法就是檢測這個數是否有效

閱讀全文

與java演算法小程序相關的資料

熱點內容
linuxc多進程 瀏覽:647
android飛行游戲 瀏覽:963
數據挖掘常見演算法 瀏覽:128
python單實例化 瀏覽:349
str中python 瀏覽:89
java的equals用法 瀏覽:845
奧維雲伺服器怎麼開通 瀏覽:171
js取得伺服器地址 瀏覽:812
起點中文網小說緩存在哪個文件夾 瀏覽:216
java瘋狂講義pdf 瀏覽:300
推有錢app在哪裡 瀏覽:745
寧波鮑斯壓縮機 瀏覽:93
新建文件夾電影2完整版演員表 瀏覽:988
空調壓縮機為什麼不能放到冷庫用 瀏覽:89
江西雲伺服器節點虛擬主機 瀏覽:997
新氧app如何測試臉型 瀏覽:688
個稅app如何查詢社保 瀏覽:495
安卓設備快充什麼時候開啟的 瀏覽:13
ipad怎麼用安卓手機傳文件 瀏覽:584
編輯程序員視頻 瀏覽:634