導航:首頁 > 編程語言 > java案例源代碼

java案例源代碼

發布時間:2024-07-10 00:39:37

❶ 幫忙給一個java菜單欄例子的源代碼

給你個小例子,已經添加註釋了。自己運行下看看效果,滿意的話記得結貼子!
import java.awt.BorderLayout;
import java.awt.CheckboxMenuItem;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestMenu extends Frame implements ActionListener{
TextArea ta; //文本區
MenuBar mb; //MenuBar 類封裝綁定到框架的菜單欄的
Menu mnFile,mnEdit,mnFormat,mnHelp; //從菜單欄部署的下拉式菜單組件
MenuItem miNew,miOpen,miSave,miSaveAs,miExit,miFont; //菜單中的所有項必須屬於類 MenuItem 或其子類之一
CheckboxMenuItem miBinary; //一個可包括在菜單中的復選框
public TestMenu(){
super("記事本"); //調用父類構造方法
ta = new TextArea("",20,20); //新建文本區,第一個參數是默認文本,第二個參數是行數,第三個是列數
/*
* BorderLayout邊框布局
* 添加文本區到Frame,BorderLayout.CENTER是居中位置
* */
add(ta,BorderLayout.CENTER);
mb = new MenuBar(); //創建菜單欄對象
/*
* 創建菜單,指定菜單名
* */
mnFile= new Menu("文件");
mnEdit= new Menu("編輯");
mnFormat= new Menu("格式");
mnHelp= new Menu("幫助");

/*
* 創建子菜單,並指定名稱
* */
miNew= new MenuItem("新建");
miOpen= new MenuItem("打開");
miSave= new MenuItem("保存");
miSaveAs= new MenuItem("另存為");
miExit= new MenuItem("退出");

miExit.addActionListener(this); //為退出菜單添加監聽

/*
* 添加上面創建的子菜單到文件菜單下
* */
mnFile.add(miNew);
mnFile.add(miOpen);
mnFile.add(miSave);
mnFile.add(miSaveAs);
mnFile.addSeparator(); //將一個分隔線或連字元添加到菜單的當前位置
mnFile.add(miExit);

miBinary= new CheckboxMenuItem("二進制"); //創建在復選框的子菜單
miFont= new MenuItem("字體"); //創建子菜單
/*
* 添加miBinary、miFont兩個子菜單到mnFormat(格式)下
* */
mnFormat.add(miBinary);
mnFormat.add(miFont);

/*
* 將文件、編輯、格式、幫助添加到菜單欄
* */
mb.add(mnFile);
mb.add(mnEdit);
mb.add(mnFormat);
mb.add(mnHelp);

setMenuBar(mb); //添加菜單欄到Frame

/*
* 關閉窗口時,關閉運行成語
* */
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public static void main(String args[]){
TestMenu tm=new TestMenu();
tm.setSize(300,200); //設置窗體的寬、高
tm.setLocation(300,100); //將組件移到新位置Component類方法
tm.setVisible(true); //設置顯示窗體,true為顯示,false為隱藏
}

/**
* 監聽事件,實現ActionListener介面的actionPerformed方法
*/
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand(); //獲取選中菜單的名稱
System.out.println(s);
if(s.equals("退出")){
System.exit(0); //停止運行程序
}
}
}

❷ 求:java實例源代碼

import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.*;
public class Counter extends Frame
{
//聲明三個面板的布局
GridLayout gl1,gl2,gl3;
Panel p0,p1,p2,p3;
JTextField tf1;
TextField tf2;
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26;
StringBuffer str;//顯示屏所顯示的字元串
double x,y;//x和y都是運算數
int z;//Z表示單擊了那一個運算符.0表示"+",1表示"-",2表示"*",3表示"/"
static double m;//記憶的數字
public Counter()
{
gl1=new GridLayout(1,4,10,0);//實例化三個面板的布局
gl2=new GridLayout(4,1,0,15);
gl3=new GridLayout(4,5,10,15);

tf1=new JTextField(27);//顯示屏
tf1.setHorizontalAlignment(JTextField.RIGHT);
tf1.setEnabled(false);
tf1.setText("0");
tf2=new TextField(10);//顯示記憶的索引值
tf2.setEditable(false);
//實例化所有按鈕、設置其前景色並注冊監聽器
b0=new Button("Backspace");
b0.setForeground(Color.red);
b0.addActionListener(new Bt());
b1=new Button("CE");
b1.setForeground(Color.red);
b1.addActionListener(new Bt());
b2=new Button("C");
b2.setForeground(Color.red);
b2.addActionListener(new Bt());
b3=new Button("MC");
b3.setForeground(Color.red);
b3.addActionListener(new Bt());
b4=new Button("MR");
b4.setForeground(Color.red);
b4.addActionListener(new Bt());
b5=new Button("MS");
b5.setForeground(Color.red);
b5.addActionListener(new Bt());
b6=new Button("M+");
b6.setForeground(Color.red);
b6.addActionListener(new Bt());
b7=new Button("7");
b7.setForeground(Color.blue);
b7.addActionListener(new Bt());
b8=new Button("8");
b8.setForeground(Color.blue);
b8.addActionListener(new Bt());
b9=new Button("9");
b9.setForeground(Color.blue);
b9.addActionListener(new Bt());
b10=new Button("/");
b10.setForeground(Color.red);
b10.addActionListener(new Bt());
b11=new Button("sqrt");
b11.setForeground(Color.blue);
b11.addActionListener(new Bt());
b12=new Button("4");
b12.setForeground(Color.blue);
b12.addActionListener(new Bt());
b13=new Button("5");
b13.setForeground(Color.blue);
b13.addActionListener(new Bt());
b14=new Button("6");
b14.setForeground(Color.blue);
b14.addActionListener(new Bt());
b15=new Button("*");
b15.setForeground(Color.red);
b15.addActionListener(new Bt());
b16=new Button("%");
b16.setForeground(Color.blue);
b16.addActionListener(new Bt());
b17=new Button("1");
b17.setForeground(Color.blue);
b17.addActionListener(new Bt());
b18=new Button("2");
b18.setForeground(Color.blue);
b18.addActionListener(new Bt());
b19=new Button("3");
b19.setForeground(Color.blue);
b19.addActionListener(new Bt());
b20=new Button("-");
b20.setForeground(Color.red);
b20.addActionListener(new Bt());
b21=new Button("1/X");
b21.setForeground(Color.blue);
b21.addActionListener(new Bt());
b22=new Button("0");
b22.setForeground(Color.blue);
b22.addActionListener(new Bt());
b23=new Button("+/-");
b23.setForeground(Color.blue);
b23.addActionListener(new Bt());
b24=new Button(".");
b24.setForeground(Color.blue);
b24.addActionListener(new Bt());
b25=new Button("+");
b25.setForeground(Color.red);
b25.addActionListener(new Bt());
b26=new Button("=");
b26.setForeground(Color.red);
b26.addActionListener(new Bt());

//實例化四個面板
p0=new Panel();
p1=new Panel();
p2=new Panel();
p3=new Panel();
//創建一個空字元串緩沖區
str=new StringBuffer();

//添加面板p0中的組件和設置其在框架中的位置和大小
p0.add(tf1);
p0.setBounds(10,25,300,40);
//添加面板p1中的組件和設置其在框架中的位置和大小
p1.setLayout(gl1);
p1.add(tf2);
p1.add(b0);
p1.add(b1);
p1.add(b2);
p1.setBounds(10,65,300,25);
//添加面板p2中的組件並設置其的框架中的位置和大小
p2.setLayout(gl2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.setBounds(10,110,40,150);
//添加面板p3中的組件並設置其在框架中的位置和大小
p3.setLayout(gl3);//設置p3的布局
p3.add(b7);
p3.add(b8);
p3.add(b9);
p3.add(b10);
p3.add(b11);
p3.add(b12);
p3.add(b13);
p3.add(b14);
p3.add(b15);
p3.add(b16);
p3.add(b17);
p3.add(b18);
p3.add(b19);
p3.add(b20);
p3.add(b21);
p3.add(b22);
p3.add(b23);
p3.add(b24);
p3.add(b25);
p3.add(b26);
p3.setBounds(60,110,250,150);
//設置框架中的布局為空布局並添加4個面板
setLayout(null);
add(p0);
add(p1);
add(p2);
add(p3);
setResizable(false);//禁止調整框架的大小
//匿名類關閉窗口
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e1)
{
System.exit(0);
}
});
setBackground(Color.lightGray);
setBounds(100,100,320,280);
setVisible(true);

}
//構造監聽器
class Bt implements ActionListener
{
public void actionPerformed(ActionEvent e2)
{
try{

if(e2.getSource()==b1)//選擇"CE"清零
{
tf1.setText("0");//把顯示屏清零
str.setLength(0);//清空字元串緩沖區以准備接收新的輸入運算數
}
else if(e2.getSource()==b2)//選擇"C"清零
{
tf1.setText("0");//把顯示屏清零
str.setLength(0);
}
else if(e2.getSource()==b23)//單擊"+/-"選擇輸入的運算數是正數還是負數
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(-x));
}
else if(e2.getSource()==b25)//單擊加號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);//清空緩沖區以便接收新的另一個運算數
y=0d;
z=0;
}
else if(e2.getSource()==b20)//單擊減號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=1;
}
else if(e2.getSource()==b15)//單擊乘號按鈕獲得x的值和z的值並清空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=2;
}
else if(e2.getSource()==b10)//單擊除號按鈕獲得x的值和z的值並空y的值
{
x=Double.parseDouble(tf1.getText().trim());
str.setLength(0);
y=0d;
z=3;
}
else if(e2.getSource()==b26)//單擊等號按鈕輸出計算結果
{
str.setLength(0);
switch(z)
{
case 0 : tf1.setText(""+(x+y));break;
case 1 : tf1.setText(""+(x-y));break;
case 2 : tf1.setText(""+(x*y));break;
case 3 : tf1.setText(""+(x/y));break;
}
}
else if(e2.getSource()==b24)//單擊"."按鈕輸入小數
{
if(tf1.getText().trim().indexOf(′.′)!=-1)//判斷字元串中是否已經包含了小數點
{

}
else//如果沒數點有小
{
if(tf1.getText().trim().equals("0"))//如果初時顯示為0
{
str.setLength(0);
tf1.setText((str.append("0"+e2.getActionCommand())).toString());
}
else if(tf1.getText().trim().equals(""))//如果初時顯示為空則不做任何操作
{
}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
}
}

y=0d;

}
else if(e2.getSource()==b11)//求平方根
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText("數字格式異常");
if(x<0)
tf1.setText("負數沒有平方根");
else
tf1.setText(""+Math.sqrt(x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b16)//單擊了"%"按鈕
{
x=Double.parseDouble(tf1.getText().trim());
tf1.setText(""+(0.01*x));
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b21)//單擊了"1/X"按鈕
{

x=Double.parseDouble(tf1.getText().trim());
if(x==0)
{

tf1.setText("除數不能為零");
}
else
{
tf1.setText(""+(1/x));
}
str.setLength(0);
y=0d;
}
else if(e2.getSource()==b3)//MC為清除內存
{
m=0d;
tf2.setText("");
str.setLength(0);
}
else if(e2.getSource()==b4)//MR為重新調用存儲的數據
{
if(tf2.getText().trim()!="")//有記憶數字
{
tf1.setText(""+m);
}
}
else if(e2.getSource()==b5)//MS為存儲顯示的數據
{

m=Double.parseDouble(tf1.getText().trim());
tf2.setText("M");
tf1.setText("0");
str.setLength(0);
}
else if(e2.getSource()==b6)//M+為將顯示的數字與已經存儲的數據相加要查看新的數字單擊MR
{
m=m+Double.parseDouble(tf1.getText().trim());
}
else//選擇的是其他的按鈕
{
if(e2.getSource()==b22)//如果選擇的是"0"這個數字鍵
{
if(tf1.getText().trim().equals("0"))//如果顯示屏顯示的為零不做操作
{

}
else
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
else if(e2.getSource()==b0)//選擇的是「BackSpace」按鈕
{
if(!tf1.getText().trim().equals("0"))//如果顯示屏顯示的不是零
{
if(str.length()!=1)
{
tf1.setText(str.delete(str.length()-1,str.length()).toString());//可能拋出字元串越界異常
}
else
{
tf1.setText("0");
str.setLength(0);
}
}
y=Double.parseDouble(tf1.getText().trim());
}
else//其他的數字鍵
{
tf1.setText(str.append(e2.getActionCommand()).toString());
y=Double.parseDouble(tf1.getText().trim());
}
}
}
catch(NumberFormatException e){
tf1.setText("數字格式異常");
}
catch( e){
tf1.setText("字元串索引越界");
}
}
}
public static void main(String args[])
{
new Counter();
}

}

❸ 求一個簡單又經典的Java與資料庫例子,要有源代碼哦!

//下面的是連接mysql的例子
package com.song.struts.mySql;

import javax.swing.JComponent;
import java.sql.*;
import java.util.*;
// import com.borland.dx.sql.dataset.*;

public class mySqlDao extends JComponent {
private String UserName="root";
private String PWD="root";
private String url;
private Connection cn;
private Statement stmt;
private ResultSet rs = null;
public mySqlDao(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch(java.lang.ClassNotFoundException e){
System.err.println("mydb() org.gjt.mm.mysql.Driver: " + e.getMessage());
}
catch(Exception e) {
e.printStackTrace();
}

}
//////////////////////////////
///返回mysql 連接,connection
/////////////////////////////
public Connection Connect(String dbname,String ip){
try{
String hostip=ip;
Properties myP = new Properties();
myP.setProperty("useUnicode","true");
myP.setProperty("characterEncoding","GB2312");
url="jdbc:mysql://"+hostip+":3306/"+dbname+"?user="+UserName+"&password="+PWD+"";
if(cn!=null){
cn.close();
}
cn=DriverManager.getConnection(url,myP);
stmt= cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.println("db connect success");
return cn;
}
catch(Exception e){
System.err.println("db connect err"+e.getMessage());
return null;
}
}
//////////////////////////////////
///關閉連接
/////////////////////////////////
public void close(){
try{
if(stmt!=null){
stmt.close();
}
if(cn!=null){
cn.close();
}
System.err.println("db colse success");
}
catch(Exception e){
System.err.println("db close err"+e.getMessage());
}
}
/////////////////////////////////////////////
// 用於進行記錄的查詢操�?,用於select 語句�?
//參數:sql語句�?
//返回:ResultSet對象
///////////////////////////////////////////
public ResultSet executeSelect(String sql) {
try {
stmt=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery(sql);
return rs;
}
catch(SQLException ex) {
System.err.println("db.executeQuery: " + ex.getMessage());
return null;
}
}
//////////////////////////////////////////////
//用於進行add或�?�update,insert,del等的記錄的操�?,
//入口參數:sql語句
//返回 :true,false
//////////////////////////////////////////////
public boolean executeUpdate(String sql) {
boolean bupdate=false;
try{
stmt=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
int rowCount = stmt.executeUpdate(sql);
if (rowCount!=0)
bupdate=true;
}
catch(SQLException ex) {
System.err.println("db.executeUpdate: " + ex.getMessage());
}
return bupdate;
}
//////////////////////////////////////////////
//用於進行表結構的操作,creat drop,modify等�??
//入口參數:sql語句
//返回 :true,false
//////////////////////////////////////////////
public boolean executeTable(String sql) {
boolean bupdate=false;
try {
stmt= cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.print("對表的操作的sqlis :||"+sql+"||");
stmt.executeUpdate(sql);
bupdate=true;
}
catch(SQLException ex) {
System.err.println("db.executeTable: "+ex.getMessage());
}
return bupdate;
}
//////////////////////////
//返回資料庫的信息
//////////////////////////
public Statement getLWPAIDStatement(){
try{
return cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
catch(java.sql.SQLException e){
System.err.println("getAISPStatement():"+e.getMessage());
return null;
}
}

public DatabaseMetaData getLWPAIDMetaData(){
try{
return cn.getMetaData();
}
catch(java.sql.SQLException e){
System.err.println("getAISPMetaData():"+e.getMessage());
return null;
}
}
public static void main(String args[]){
mySqlDao a=new mySqlDao();
a.Connect("mydb", "localhost");
int b=-100;
ResultSet rs=a.executeSelect("select max(bill_id) from t_bill limit 1");
try{
while(rs.next()){
System.out.println("is in");
b=rs.getInt(1);
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println(b);
// java.util.Date date=new java.util.Date();
// System.out.println(date.toString());
// a.executeTable("insert into t_user values(100,'123','1345')");
// a.executeTable("update t_user set insert_date='"+date.toString()+"' where user_id=100");
a.close();

System.out.print(new pub().asc2unicode("�?!"));
}
}

❹ 高分求兩個簡單的JAVA設計源代碼

上面 wukun12同學寫的不錯,但我想還不能運行,並且還不太完善。我給個能運行的:(注意:文件名為:Test.java)

//要實現對象間的比較,就必須實現Comparable介面,它裡面有個compareTo方法
//Comparable最好使用泛型,這樣,無論是速度還是代碼量都會減少
@SuppressWarnings("unchecked")
class Student implements Comparable<Student>{

private String studentNo; //學號
private String studentName; //姓名
private double englishScore; //英語成績
private double computerScore; //計算機成績
private double mathScore; //數學成績
private double totalScore; //總成績

//空構造函數
public Student() {}

//構造函數
public Student(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
this.studentNo = studentNo;
this.studentName = studentName;
this.englishScore = englishSocre;
this.computerScore = computerScore;
this.mathScore = mathScore;
}

//計算總成績
public double sum() {

this.totalScore = englishScore+computerScore+mathScore;
return totalScore;
}

//計算評測成績
public double testScore() {

return sum()/3;
}

//實現compareTO方法
@Override
public int compareTo(Student student) {
double studentTotal = student.getTotalScore();
return totalScore==studentTotal?0:(totalScore>studentTotal?1:-1);
}

//重寫toString方法
public String toString(){
return "學號:"+this.getStudentNo()+" 姓名:"+this.getStudentName()+" 英語成績:"+this.getEnglishScore()+" 數學成績:"+this.getMathScore()+" 計算機成績:"+this.getComputerScore()+" 總成績:"+this.getTotalScore();
}

//重寫equals方法
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(!(obj instanceof Student)){
return false;
}
Student student = (Student)obj;
if(this.studentNo.equals(student.getStudentName())) { //照現實來說,比較是不是同一個學生,應該只是看他的學號是不是相同
return true;
} else {
return false;
}

}

/*以下為get和set方法,我個人認為,totalScore的set的方法沒必要要,因為它是由其它成績計算出來的
在set方法中,沒設置一次值,調用一次sum方法,即重新計算總成績
*/
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
sum();
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
sum();
}
public double getEnglishScore() {
return englishScore;
}
public void setEnglishScore(double englishScore) {
this.englishScore = englishScore;
sum();
}
public double getComputerScore() {
return computerScore;
}
public void setComputerScore(double computerScore) {
this.computerScore = computerScore;
sum();
}
public double getMathScore() {
return mathScore;
}
public void setMathScore(double mathScore) {
this.mathScore = mathScore;
sum();
}
public double getTotalScore() {
return totalScore;
}

}

//Student子類學習委員類的實現
class StudentXW extends Student {

//重寫父類Student的testScore()方法
@Override
public double testScore() {
return sum()/3+3;
}

public StudentXW() {}

//StudentXW的構造函數
public StudentXW(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//Student子類班長類的實現
class StudentBZ extends Student {

//重寫父類Student的testScore()方法
@Override
public double testScore() {
return sum()/3+5;
}

public StudentBZ() {}

//StudentXW的構造函數
public StudentBZ(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//測試類
public class Test {

public static void main(String[] args) {

//生成若干個student類、StudentXW類、StudentBZ類
Student student1 = new Student("s001","張三",70.5,50,88.5);
Student student2 = new Student("s002","李四",88,65,88.5);
Student student3 = new Student("s003","王五",67,77,90);
StudentXW student4 = new StudentXW("s004","李六",99,88,99.5);
StudentBZ student5 = new StudentBZ("s005","朱漆",56,65.6,43.5);

Student[] students = {student1,student2,student3,student4,student5};

for(int i = 0 ; i<students.length; i++){
double avgScore = students[i].testScore();
System.out.println(students[i].getStudentName()+"學生的評測成績為:"+ avgScore+"分");
}

}
}
運行結果為:
張三學生的評測成績為:69.66666666666667分
李四學生的評測成績為:80.5分
王五學生的評測成績為:78.0分
李六學生的評測成績為:98.5分
朱漆學生的評測成績為:60.03333333333333分

❺ 求Java高手給一簡單的源代碼(200行以下),最好有註解和一段簡單的介紹

//聲明包
package cn.jbit.classandobject;
//導入包
import java.util.Scanner;
/**
* 上機階段4:登錄並購買商品
*/
// 聲明類Goods
public class Goods
{
// 聲明String類型的數組:goods,並初始化。
String[] goods = new String[] { "電風扇", "洗衣機", "電視機", "冰 箱", "空調機" }; // 定義數組是干什麼用的
// 聲明double類型的數組:price,並初始化。
double[] price = new double[] { 124.23, 4500, 8800.90, 5000.88, 4456,
12000.46 };
// 聲明返回值類型為:boolean的login()方法
public boolean login()
{
// 聲明變數flag,類型為boolean,初始值為:false,作為是否登錄成功的標志
boolean flag = false;
// 鍵盤輸入
Scanner input = new Scanner(System.in);
// 列印
System.out.print("請輸入用戶名: ");
// 聲明變數name,接收輸入用戶名
String name = input.next();
// 列印
System.out.print("請輸入密碼: ");
// 聲明變數pwd,接收輸入密碼
String pwd = input.next();
// if判斷用戶名和密碼是否正確
if (name.equals("TOM") && pwd.equals("123"))
{
// 列印
System.out.println("登錄成功! ");
// 修改是否登錄成功的標志
flag = true;
}
// else情況
else
{
// 列印
System.out.println("用戶名或密碼不匹配,登錄失敗!");
}
// 返回是否登錄成功的標志:成功(true),失敗(false)
return flag;// 這段代碼為什麼要加返回值
}
// 聲明返回值為StringBuffer類型的方法change(double d),參數為double類型的d
public StringBuffer change(double d)// 這是什麼意思啊
{
// StringBuffer str:聲明StringBuffer類型的變數str
// String.valueOf(d):獲取d的字元串值
// new StringBuffer(String.valueOf(d)):實例化str,調用了StringBuffer的構造方法
StringBuffer str = new StringBuffer(String.valueOf(d));// 這一句
// str.indexOf("."):返回第一個.所在位置:如果該值返回大於等於4,則進入for循環,否則跳過
for (int i = str.indexOf(".") - 3; i > 0; i = i - 3)
{// 這一句
// 在i出添加,如8,800.9
str.insert(i, ',');// 還有這一句
}
// 返回StringBuffer類型的字元串
return str;
}
// 聲明返回值為void的方法showGoods()
public void showGoods()
{
// 列印
System.out.print("*********歡迎進入商品批發城*********");
// 列印
System.out.print("\n\t編號\t商品\t價格\n");
// for循環輸出商品:goods.length用到開始聲明的goods來獲取數組長度
for (int i = 0; i < goods.length; i++)
{
// 列印:因為數組從0開始,而商品只能從1開始,所以i+1。\t製表符
System.out.print("\t" + (i + 1));
// 列印第i個商品
System.out.print("\t" + goods[i]);
// 列印第i個商品的價格。\n回車
System.out.print("\t" + change(price[i]) + "\n");
}
// 列印
System.out.println("**********************************");
}
// 主方法
public static void main(String[] args)
{
// 鍵盤輸入
Scanner input = new Scanner(System.in);
// 聲明Goods類的對象g,並實例化
Goods g = new Goods();
// 聲明int變數serial, num
int serial, num;
// 聲明double變數total
double total = 0;
// 判斷是否登錄成功
if (g.login())
{
// 列印商品信息
g.showGoods();
// 輸入商品編號
System.out.print("請輸入您批發的商品編號:");
// 接收
serial = input.nextInt();
// 輸入批發數量
System.out.print("請輸入批發數量:");
// 接收
num = input.nextInt();
// 計算總金額:price數組是從0開始的,商品數量是從1開始,第一個商品對應第0個價格
total = g.price[serial - 1] * num;// 計算總金額 //這一句
// 列印總金額
System.out.print("您需要付款:" + g.change(total));
}
}
}

❻ Java100行以上源代碼,至少五個class以及一個interface,可以簡單點

下面是一個可能的Java源代碼,它包含了一個介面租沖薯(Shape)和五個類(Circle, Rectangle, Triangle, Square 和 Main)。它的功能是計算不同形狀的面積和周長。
//定義一個介面Shape,有兩判指個抽象方法:getArea()和getPerimeter()interface Shape { double getArea(); double getPerimeter();
}//定義一個類Circle,實現Shape介面class Circle implements Shape { //定義一個私有屬性radius,表示圓的半徑
private double radius; //定義一個公有構造方法,用於初始化radius
public Circle(double radius) { this.radius = radius;
} //實現getArea()方法,返回圓的面積
public double getArea() { return Math.PI * radius * radius;
} //實現getPerimeter()方法,返回圓的周長
public double getPerimeter() { return Math.PI * radius * 2;
}
}//定義一個類Rectangle,實現Shape介面class Rectangle implements Shape { //定義兩個私有屬性width和height,表示矩形的寬度和高度
private double width; private double height; //定義一個公有構造方法,用於初始化width和height
public Rectangle(double width, double height) { this.width = width; this.height = height;
} //實現getArea()方法,返回矩形的面積
public double getArea() { return width * height;
} //實現getPerimeter()方法,返回矩形的周長
public double getPerimeter() { return (width + height) *2;
}
}//定義一個類Triangle,實現Shape介面class Triangle implements Shape { //定義三個私有屬性a,b,c表示三角形的三條邊長
private double a; private double b; private double c; //定義一個公有構造方法,用於初始化a,b,c,並檢查是否滿足三角形條件(任意兩邊之和大於第三邊)
public Triangle(double a, double b, double c) throws Exception{ if (a + b > c && a + c > b && b + c > a) {
this.a = a; this.b = b;
this.c = c;
} else {
throw new Exception("Invalid triangle");
}
} //實現getArea()方法,返回三角形的面積(使用海倫公式)
public double getArea() { //計算半周長p
double p = (a + b + c) /2; //計算並返回面積s(使用Math.sqrt()函數求平方根)
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
} //實現getPerimeter()方法,返回三角形的周長
public double getPerimeter(){ return a + b + c;
}
}//定義一個類Square,繼承Rectangle類,並重寫構造方法和toString()方法class Square extends Rectangle { //重寫構造方法,在調用父類構造方法時傳入相弊者同的參數side作為width和height
public Square(double side){ super(side, side);
} //重寫toString()方法,在原來基礎上加上"Square:"前綴,並只顯示side屬性而不顯示width和height屬性(使用String.format()函數格式化字元串)
@Override
public String toString(){ return String.format("Square: side=%.2f", super.width); /* 或者直接使用super.getPerimeter()/4作為side */
/* return String.format("Square: side=%.2f", super.getPerimeter()/4); */

/* 注意:不能直接訪問super.side屬性,

❼ 求一個簡單又經典的JAVA資料庫連接的例子,要有源代碼哦!

我就弄的用戶登入的代碼吧.這個挺簡單的.
這是題目:
用戶登陸驗證:
1.創建資料庫Test,並新建用戶表users
欄位包含:username varchar(20) not null
userpwd varchar(20) not null

在JBUILDER中編寫Long類,實現登陸界面,並在用戶輸入用戶名和密碼後,
完成按紐的單擊事件,對用戶輸入的數據進行驗證,
(需要嚴整數據是否為空,密碼長度必須是15位),
並實現與資料庫的連接,將用戶輸入的用戶名密碼與表中的記錄比較,
若用戶名正確且密碼正確,彈出提示框告知登陸成功,否則登陸失敗。

這是代碼:
//連接資料庫
boolean isLogin(String name,String pwd){
boolean flag=false;
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
//載入驅動
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//連接資料庫
try {
conn=DriverManager.getConnection("jdbc:odbc:login");
String sql="select * from [user] where username=? and userpwd=?";
pst=conn.prepareStatement(sql);
pst.setString(1,name);
pst.setString(2,pwd);
rs=pst.executeQuery();
if(rs.next())
flag=true;
} catch (Exception ex) {
ex.printStackTrace();
}finally{
try {
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return flag;

}
//驗證方法
public void jButton1_actionPerformed(ActionEvent e) {
String name=jTextField1.getText();
String pwd=jTextField2.getText();
//錯誤處理
if(name.equals("")||pwd.equals(""))
JOptionPane.showMessageDialog(this,"請輸入完整的信息");
else {
if(isLogin(name,pwd))
JOptionPane.showMessageDialog(this,"登陸成功");
else
JOptionPane.showMessageDialog(this,"用戶名或密碼錯誤");

}

}
}
.....
.....
這是在事件里寫的,

閱讀全文

與java案例源代碼相關的資料

熱點內容
viper4android安卓60 瀏覽:485
java軟體源碼 瀏覽:159
空氣壓縮機的類型 瀏覽:352
centos圖形命令行界面切換 瀏覽:237
新京報新聞APP什麼時候有的 瀏覽:818
華為手機文件夾重命名空白 瀏覽:742
通俗理解螞蟻演算法 瀏覽:555
俠盜獵車手怎麼注冊伺服器 瀏覽:341
去商場吃飯預約什麼app 瀏覽:776
nginx不能解析php 瀏覽:135
安卓系統如何轉換中文 瀏覽:316
小米手機用什麼下載非官方app 瀏覽:760
linux修改readonly 瀏覽:32
演算法時代我們能做什麼 瀏覽:928
牛津英語搭配詞典pdf 瀏覽:284
慧連a6怎麼連接安卓 瀏覽:235
python使用什麼編譯器最好 瀏覽:52
小程序編譯藍屏 瀏覽:947
程序員賽車的gif 瀏覽:413
購買新車能用到什麼app 瀏覽:775