Java2实用教程上机实践9,10,11

发布于:2025-02-11 ⋅ 阅读:(90) ⋅ 点赞:(0)

前言

大家好呀,大家肯定遇到过学校布置的作业不会做的情况吧?这个时候大量的网上找资料,找如何做这道题,为了帮助用Java2实用教程(耿祥义 张跃平主编)的学子们拿满平时分,这里整理出这本书中比较难的上机实践9(组件与事件处理)10(输入输出流)11(JDBC数据库操作)源码,请注意由于是作者手动复制粘贴,可能会出现类名错误或者包名不匹配等错误,自行调整即可,希望能帮助到有需要的人,感谢观看

上机实践9:组件与事件处理

实验 1 算术测试

MainClass.java

public class MainClass {
    public static void main(String args[]) {
        cqut.test6.ComputerFrame frame;
        frame = new cqut.test6.ComputerFrame();
        frame.setTitle("算术测试");
        frame.setBounds(100, 100, 650, 180);
    }
}
ComputerFrame.java
public class ComputerFrame extends JFrame {
    JMenuBar menubar;
    JMenu choiceGrade;
    JMenuItem grade1, grade2;
    JTextField textOne, textTwo, textResult;
    JButton getProblem, giveAnwser;
    JLabel operatorLabel, message;
    Teacher teacherZhang;

    ComputerFrame() {
        teacherZhang = new Teacher();
        teacherZhang.setMaxInteger(20);
        setLayout(new FlowLayout());
        menubar = new JMenuBar();
        choiceGrade = new JMenu("选择级别");
        grade1 = new JMenuItem("幼⼉级别");
        grade2 = new JMenuItem("⼉童级别");
        grade1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                teacherZhang.setMaxInteger(10);
            }
        });
        grade2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                teacherZhang.setMaxInteger(50);
            }
        });
        choiceGrade.add(grade1);
        choiceGrade.add(grade2);
        menubar.add(choiceGrade);
        setJMenuBar(menubar);
        textOne = new JTextField(5);
        textTwo = new JTextField(5);
        textResult = new JTextField(5);
        operatorLabel = new JLabel("+");
        operatorLabel.setFont(new Font("Arial", Font.BOLD, 20));
        message = new JLabel("你还没有回答呢");
        getProblem = new JButton("获取题⽬");
        giveAnwser = new JButton("确认答案");
        add(getProblem);
        add(textOne);
        add(operatorLabel);
        add(textTwo);
        add(new JLabel("="));
        add(textResult);
        add(giveAnwser);
        add(message);
        textResult.requestFocus();
        textOne.setEditable(false);
        textTwo.setEditable(false);
        getProblem.setActionCommand("getProblem");
        textResult.setActionCommand("answer");
        giveAnwser.setActionCommand("answer");
        teacherZhang.setJTextField(textOne, textTwo, textResult);
        teacherZhang.setJLabel(operatorLabel, message);
        getProblem.addActionListener(teacherZhang);
        giveAnwser.addActionListener(teacherZhang);
        textResult.addActionListener(teacherZhang);
        setVisible(true);
        validate();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
}

Teacher.java

import java.util.Random;
import java.awt.event.*;
import javax.swing.*;
public class Teacher implements ActionListener {
    int numberOne, numberTwo;
    String operator = "";
    boolean isRight;
    Random random; //⽤于给出随机数
    int maxInteger; //题⽬中最⼤的整数
    JTextField textOne, textTwo, textResult;
    JLabel operatorLabel, message;

    Teacher() {
        random = new Random();
    }

    public void setMaxInteger(int n) {
        maxInteger = n;
    }

    public void actionPerformed(ActionEvent e) {
        String str = e.getActionCommand();
        if (str.equals("getProblem")) {
            numberOne = random.nextInt(maxInteger) + 1;//1 ⾄ maxInteger 之间的随机数;
            numberTwo = random.nextInt(maxInteger) + 1;
            double d = Math.random(); // 获取(0,1)之间的随机数
            if (d >= 0.5)
                operator = "+";
            else
                operator = "-";
            textOne.setText("" + numberOne);
            textTwo.setText("" + numberTwo);
            operatorLabel.setText(operator);
            message.setText("请回答");
            textResult.setText(null);
        } else if (str.equals("answer")) {
            String answer = textResult.getText();
            try {
                int result = Integer.parseInt(answer);
                if (operator.equals("+")) {
                    if (result == numberOne + numberTwo)
                        message.setText("你回答正确");
                    else
                        message.setText("你回答错误");
                } else if (operator.equals("-")) {
                    if (result == numberOne - numberTwo)
                        message.setText("你回答正确");
                    else
                        message.setText("你回答错误");
                }
            } catch (NumberFormatException ex) {
                message.setText("请输⼊数字字符");
            }
        }
    }

    public void setJTextField(JTextField... t) {
        textOne = t[0];
        textTwo = t[1];
        textResult = t[2];
    }

    public void setJLabel(JLabel... label) {
        operatorLabel = label[0];
        message = label[1];
    }
}

实验 2 布局与⽇历

CalenDdarPanel.java

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

public class CalendarPanel extends JPanel {
    GiveCalendar calendar;
    LocalDate[] dataArrays;
    public LocalDate currentDate;
    String name[] = {"⽇", "⼀", "⼆", "三", "四", "五", "六"};

    public CalendarPanel() {
        calendar = new GiveCalendar();
        currentDate = LocalDate.now();
        dataArrays = calendar.getCalendar(currentDate);
        showCalendar(dataArrays);
    }

    public void showCalendar(LocalDate[] dataArrays) {
        removeAll();
        GridLayout grid = new GridLayout(7, 7);
        setLayout(grid);
        JLabel[] titleWeek = new JLabel[7];
        JLabel[] showDay = new JLabel[42];
        for (int i = 0; i < 7; i++) {
            titleWeek[i] = new JLabel(name[i], JLabel.CENTER);
add(titleWeek[i]);
        }
        for (int i = 0; i < 42; i++) {
            showDay[i] = new JLabel("", JLabel.CENTER);
        }
        for (int k = 7, i = 0; k < 49; k++, i++) {
            add(showDay[i]);
        }
        int space = printSpace(dataArrays[0].getDayOfWeek());
        for (int i = 0, j = space + i; i < dataArrays.length; i++, j++) {
            showDay[j].setText("" + dataArrays[i].getDayOfMonth());
        }
        repaint();
    }

    public void setNext() {
        currentDate = currentDate.plusMonths(1);
        dataArrays = calendar.getCalendar(currentDate);
        showCalendar(dataArrays);
    }

    public void setPrevious() {
        currentDate = currentDate.plusMonths(-1);
        dataArrays = calendar.getCalendar(currentDate);
        showCalendar(dataArrays);
    }

    public int printSpace(DayOfWeek x) {
        int n = 0;
        switch (x) {
            case SUNDAY:
                n = 0;
                break;
            case MONDAY:
                n = 1;
                break;
            case TUESDAY:
                n = 2;
                break;
            case WEDNESDAY:
                n = 3;
                break;
            case THURSDAY:
                n = 4;
                break;
            case FRIDAY:
                n = 5;
                break;
            case SATURDAY:
                n = 6;
                break;
        }
        return n;
    }
}
GiveCalendar.java
import java.time.*;
public class GiveCalendar {
    public LocalDate [] getCalendar(LocalDate date) {
        date = date.withDayOfMonth(1);
        int days = date.lengthOfMonth();
        LocalDate dataArrays[] = new LocalDate[days];
        for (int i = 0; i < days; i++) {
            dataArrays[i] = date.plusDays(i);
        }
        return dataArrays;
    }
}
ShowCalendar.java
public class ShowCalendar extends JFrame {
    CalendarPanel showCalendar;
    JButton nextMonth;
    JButton previousMonth;
    JLabel showYear, showMonth;

    public ShowCalendar() {
        showCalendar = new CalendarPanel();
        add(showCalendar);
        nextMonth = new JButton("下⼀个⽉");
        previousMonth = new JButton("上⼀个⽉");
        showYear = new JLabel();
        showMonth = new JLabel();
        JPanel pNorth = new JPanel();
        showYear.setText("" + showCalendar.currentDate.getYear() + "年");
        showMonth.setText("" + showCalendar.currentDate.getMonthValue() + "⽉");
        pNorth.add(showYear);
        pNorth.add(previousMonth);
        pNorth.add(nextMonth);
        pNorth.add(showMonth);
        add(pNorth,java.awt.BorderLayout.NORTH);
        nextMonth.addActionListener((e) -> {
            showCalendar.setNext();
            showYear.setText("" + showCalendar.currentDate.getYear() + "年");
            showMonth.setText("" + showCalendar.currentDate.getMonthValue() + "⽉");
        });
        previousMonth.addActionListener((e) -> {
            showCalendar.setPrevious();
            showYear.setText("" + showCalendar.currentDate.getYear() + "年");
            showMonth.setText("" + showCalendar.currentDate.getMonthValue() + "⽉");
        });
        setSize(290, 260);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String args[]) {
        new ShowCalendar();
    }
}

实验 3 英语单词拼写训练

LetterLabel.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class LetterLabel extends JTextField implements FocusListener {
    LetterLabel() {
        setEditable(false);
        addFocusListener(this);//【代码 1】 //将当前对象注册为⾃⾝的焦点视器
        setBackground(Color.white);
        setFont(new Font("Arial", Font.PLAIN, 30));
    }

    public static LetterLabel[] getLetterLabel(int n) {
        LetterLabel a[] = new LetterLabel[n];
        for (int k = 0; k < a.length; k++)
            a[k] = new LetterLabel();
        return a;
    }

    public void focusGained(FocusEvent e) {
        setBackground(Color.cyan);
    }

    public void focusLost(FocusEvent e) {
        setBackground(Color.white);
    }

    public void setText(char c) {
        setText("" + c);
    }
}
RondomString.java
public class RondomString { //负责随机排列单词中的字⺟
    String str = "";

    public String getRondomString(String s) {
        StringBuffer strBuffer = new StringBuffer(s);
        int m = strBuffer.length();
        for (int k = 0; k < m; k++) {
            int index = (int) (Math.random() * strBuffer.length());//Math.random()返回(0,1)之间的随机数
            char c = strBuffer.charAt(index);
            str = str + c;
            strBuffer = strBuffer.deleteCharAt(index);
        }
        return str;
    }
}
SpellingWordFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SpellingWordFrame extends JFrame implements KeyListener, ActionListener {
    JTextField inputWord;
    JButton button;
    test8.LetterLabel label[];
    JPanel northP, centerP;
    Box wordBox;
    String hintMessage = "⽤⿏标单击字⺟,按左右箭头交换字⺟,将其排列成所输⼊的单词";
    JLabel messaageLabel = new JLabel(hintMessage);
    String word = "";

    SpellingWordFrame() {
        inputWord = new JTextField(12);
        button = new JButton("确定");
        button.addActionListener(this);
        inputWord.addActionListener(this);
        northP = new JPanel();
        northP.add(new JLabel("输⼊单词:"));
        northP.add(inputWord);
        northP.add(button);
        centerP = new JPanel();
        wordBox = Box.createHorizontalBox();
        centerP.add(wordBox);
        add(northP, BorderLayout.NORTH);
        add(centerP, BorderLayout.CENTER);
        add(messaageLabel, BorderLayout.SOUTH);
        setBounds(100, 100, 350, 180);
        setVisible(true);
        validate();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        word = inputWord.getText();
        int n = word.length();
        test8.RondomString rondom = new test8.RondomString();
        String randomWord = rondom.getRondomString(word);
        wordBox.removeAll();
        messaageLabel.setText(hintMessage);
        if (n > 0) {
            label = test8.LetterLabel.getLetterLabel(n);
            for (int k = 0; k < label.length; k++) {
                label[k].setText("" + randomWord.charAt(k));
                wordBox.add(label[k]);
                label[k].addKeyListener(this); //将当前窗⼝注册为 label[k]的键盘监视器
            }
            validate();
            inputWord.setText(null);
            label[0].requestFocus();
        }
    }

    public void keyPressed(KeyEvent e) {
        test8.LetterLabel sourceLabel = (test8.LetterLabel) e.getSource();
        int index = -1;
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            for (int k = 0; k < label.length; k++) {
                if (label[k] == sourceLabel) {
                    index = k;
                    break;
                }
            }
            if (index != 0) { //交换⽂本框中的字⺟
                String temp = label[index].getText();
                label[index].setText(label[index - 1].getText());
                label[index - 1].setText(temp);
                label[index - 1].requestFocus();
            }
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //判断按下的是否是→键
            for (int k = 0; k < label.length; k++) {
                if (label[k] == sourceLabel) {
                    index = k;
                    break;
                }
            }
            if (index != label.length - 1) {
                String temp = label[index].getText();
                label[index].setText(label[index + 1].getText());
                label[index + 1].setText(temp);
                label[index + 1].requestFocus();
            }
        }
        validate();
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
        String success = "";
        for (int k = 0; k < label.length; k++) {
            String str = label[k].getText();
            success = success + str;
        }
        if (success.equals(word)) {
            messaageLabel.setText("恭喜你,你成功了");
            for (int k = 0; k < label.length; k++) {
                label[k].removeKeyListener(this);
                label[k].removeFocusListener(label[k]);
                label[k].setBackground(Color.white);
            }
            inputWord.requestFocus();
        }
    }
}
WordMainClass.java
public class WordMainClass {
    public static void main(String args[]) {
        new SpellingWordFrame();
    }
}

实验 4 字体对话框

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

public class FontDialog extends JDialog implements ItemListener, ActionListener {
    FontFamilyNames fontFamilyNames;
    int fontSize = 38;
    String fontName;
    JComboBox fontNameList, fontSizeList;
    JLabel label;
    Font font;
    JButton yes, cancel;
    static int YES = 1, NO = 0;
    int state = -1;

    FontDialog(JFrame f) {
        super(f);
        setTitle("字体对话框");
        font = new Font("宋体", Font.PLAIN, 12);
        fontFamilyNames = new FontFamilyNames();
        setModal(true);
        yes = new JButton("Yes");
        cancel = new JButton("cancel");
        yes.addActionListener(this);
        cancel.addActionListener(this);
        label = new JLabel("hello,奥运", JLabel.CENTER);
        fontNameList = new JComboBox();
        fontSizeList = new JComboBox();
        String name[] = fontFamilyNames.getFontName();
        fontNameList.addItem("字体");
        for (int k = 0; k < name.length; k++)
            fontNameList.addItem(name[k]);
        fontSizeList.addItem("大小");
        for (int k = 8; k < 72; k = k + 2)
            fontSizeList.addItem(new Integer(k));
        fontNameList.addItemListener(this);
        fontSizeList.addItemListener(this);
        JPanel pNorth = new JPanel();
        pNorth.add(fontNameList);
        pNorth.add(fontSizeList);
        add(pNorth, BorderLayout.NORTH);
        add(label, BorderLayout.CENTER);
        JPanel pSouth = new JPanel();
        pSouth.add(yes);
        pSouth.add(cancel);
        add(pSouth, BorderLayout.SOUTH);
        setBounds(100, 100, 280, 170);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        validate();
    }
    public void itemStateChanged(ItemEvent e) {
        if (e.getSource() == fontNameList) {
            fontName = (String) fontNameList.getSelectedItem();
            font = new Font(fontName, Font.PLAIN, fontSize);
        } else if (e.getSource() == fontSizeList) {
            Integer m = (Integer) fontSizeList.getSelectedItem();
            fontSize = m.intValue();
            font = new Font(fontName, Font.PLAIN, fontSize);
        }
        label.setFont(font);
        label.repaint();
        validate();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == yes) {
            state = YES;
            setVisible(false);
        } else if (e.getSource() == cancel) {
            state = NO;
            setVisible(false);
        }
    }

    public int getState() {
        return state;
    }

    public Font getFont() {
        return font;
    }
}
FontDialogMainClass.java
public class FontDialogMainClass {
    public static void main(String args[]) {
        FrameHaveDialog win = new FrameHaveDialog();
    }
}
FontFamilyNames.java
import java.awt.GraphicsEnvironment;
public class FontFamilyNames {
    String allFontNames[];

    public String[] getFontName() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        allFontNames = ge.getAvailableFontFamilyNames();
        return allFontNames;
    }
}
FrameHaveDialog.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class FrameHaveDialog extends JFrame implements ActionListener {
    JTextArea text;
    JButton buttonFont;

    FrameHaveDialog() {
        buttonFont = new JButton("设置字体");
        text = new JTextArea("java2实用教程");
        buttonFont.addActionListener(this);
        add(buttonFont, BorderLayout.NORTH);
        add(text);
        setBounds(60, 60, 300, 300);
        setVisible(true);
        validate();
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonFont) {
            FontDialog dialog = new FontDialog(this);
            dialog.setVisible(true);
            if (dialog.getState() == FontDialog.YES) {
                text.setFont(dialog.getFont());
                text.repaint();
            }
            if (dialog.getState() == FontDialog.NO) {
                text.repaint();
            }
        }
    }
}

上机实践 10 输⼊和输出流

实验 1 分析成绩单

AnalysisResult.java
import java.io.*;

public class AnalysisResult {
    public static void main(String[] args) {
        File fRead = new File("score.txt");
        File fWrite = new File("scoreAnalysis.txt");
        try{
            Writer out = new FileWriter(fWrite,true);
            BufferedWriter bufferWrite = new BufferedWriter(out);
            Reader in = new FileReader(fRead);
            BufferedReader bufferRead =new BufferedReader(in) ;
            String str = null;
            while((str=bufferRead.readLine())!=null) {
                double totalScore= Fenxi.getTotalScore(str);
                str = str+" 总分:"+totalScore;
                System.out.println(str);
                bufferWrite.write(str);
                bufferWrite.newLine();
            }
            bufferRead.close();
            bufferWrite.close();
        }
        catch(IOException e) {
            System.out.println(e.toString());
        }
    }
}
Fenxi.java
import java.util.*;

public class Fenxi {
    public static double getTotalScore(String s) {
        Scanner scanner = new Scanner(s);
        scanner.useDelimiter("[^0123456789.]+");
        double totalScore=0;
        while(scanner.hasNext()){
            try{ double score = scanner.nextDouble();
                totalScore = totalScore+score;
            }
            catch(InputMismatchException exp){
                String t = scanner.next();
            }
        }
        return totalScore;
    }
}

实验 2 统计英⽂单词

OutputWordMess.java
import java.util.*;

public class OutputWordMess {
    public static void main(String args[]) {
        Vector<String> allWord,noSameWord;
        WordStatistic statistic =new WordStatistic();
        statistic.setFileName("hello.txt");
        statistic.wordStatistic();
        allWord=statistic.getAllWord();
        noSameWord=statistic.getNoSameWord();
        System.out.println("共有"+allWord.size()+"个英⽂单词");
        System.out.println("有"+noSameWord.size()+"个互不相同英⽂单词");
        System.out.println("按出现频率排列:");
        int count[]=new int[noSameWord.size()];
        for(int i=0;i<noSameWord.size();i++) {
            String s1 = noSameWord.elementAt(i);
            for(int j=0;j<allWord.size();j++) {
                String s2=allWord.elementAt(j);
                if(s1.equals(s2))
                    count[i]++;
            }
        }
        for(int m=0;m<noSameWord.size();m++) {
            for(int n=m+1;n<noSameWord.size();n++) {
                if(count[n]>count[m]) {
                    String temp=noSameWord.elementAt(m);
                    noSameWord.setElementAt(noSameWord.elementAt(n),m);
                    noSameWord.setElementAt(temp,n);
                    int t=count[m];
                    count[m]=count[n];
                    count[n]=t;
                }
            }
        }
        for(int m=0;m<noSameWord.size();m++) {
            double frequency=(1.0*count[m])/allWord.size();
            System.out.printf("%s:%-7.3f",noSameWord.elementAt(m),frequency);
        }
    }
}
WordStatistic.java
import java.io.*;
import java.util.*;

public class WordStatistic {
    Vector<String> allWord,noSameWord;
    File file = new File("english.txt");
    Scanner sc = null;
    String regex;
    WordStatistic() {
        allWord = new Vector<String>();
        noSameWord = new Vector<String>();
        regex= "[\\s\\d\\p{Punct}]+";
        try{
            sc = new Scanner(file) ;
            sc.useDelimiter(regex);
        }
        catch(IOException exp) {
            System.out.println(exp.toString());
        }
    }
    void setFileName(String name) {
        file = new File(name);
        try{
            sc = new Scanner(file);
            sc.useDelimiter(regex);
        }
        catch(IOException exp) {
            System.out.println(exp.toString());
        }
    }
    public void wordStatistic() {
        try{
            while(sc.hasNext()){
                String word = sc.next();
                allWord.add(word);
                if(!noSameWord.contains(word))
                    noSameWord.add(word);
            }

        }
        catch(Exception e){}
    }
    public Vector<String> getAllWord() {
        return allWord;
    }
    public Vector<String> getNoSameWord() {
        return noSameWord;
    }
}

实验 3 读取压缩⽂件

ReadZipFile.java
import java.io.*;
import java.util.zip.*;

public class ReadZipFile {
    public static void main(String[] args) {
        File f=new File("book.zip");
        File dir=new File("mybook");
        byte b[]=new byte[100];
        dir.mkdir();
        try{
            ZipInputStream in=new ZipInputStream(new FileInputStream(f));
            ZipEntry zipEntry=null;
            while((zipEntry=in.getNextEntry())!=null) {
                File file=new File(dir,zipEntry.getName());
                FileOutputStream out=new  FileOutputStream(file);
                int n=-1;
                System.out.println(file.getAbsolutePath()+"的内容:");
                while((n=in.read(b,0,100))!=-1) {
                    String str=new String(b,0,n);
                    System.out.println(str);
                    out.write(b,0,n);
                }
                out.close();
            }
            in.close();
        }
        catch(IOException ee) {
            System.out.println(ee);
        }
    }
}

上机实践 11 JDBC 数据库操作

实验 1 抽取样本

ComputerAverPrice.java

public static void main(String args[]) {
        Connection con=null;
        Statement sql;
        ResultSet rs;
        try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        }
        catch(Exception e){ }
        try{
            con = DriverManager.getConnection("jdbc:Access://Book.accdb","","");
        }
        catch(SQLException e){
            System.out.println(e);
        }
        try{
            sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            rs=sql.executeQuery("SELECT*FROM bookList");
            rs.last();
            int max = rs.getRow();
            System.out.println("表共有"+max+"条记录,随机抽取 10 条记录:");
            int [] a =GetRandomNumber.getRandomNumber(max,10);
            float sum = 0;
            for(int i:a){
               rs.setFetchDirection(i);
                float price = rs.getFloat(3);
                sum = sum+price;
            }
            con.close();
            System.out.println("平均价格:"+sum/a.length);
        }
        catch(SQLException e) { }
    }
}
etRandomNumber.java
public class GetRandomNumber {
    public static int[] getRandomNumber(int max, int amount) {
        Vector<Integer> vector = new Vector<Integer>();
        for (int i = 1; i <= max; i++) {
            vector.add(i);
        }
        int result[] = new int[amount];
        while (amount > 0) {
            int index = new Random().nextInt(vector.size());
            int m = vector.elementAt(index);
            vector.removeElementAt(index);
            result[amount - 1] = m;
            amount--;
        }
        return result;
    }
}


实验 2 ⽤户转账

 TurnMoney.java
import java.sql.*;

public class TurnMoney {
    public static void main(String args[]) {
        Connection con = null;
        Statement sql;
        ResultSet rs;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("" + e);
        }
        try {
            double n = 100;
            con = DriverManager.getConnection("jdbc:odbc:tom", "", "");
            con.setAutoCommit(false);
            sql = con.createStatement();
            rs = sql.executeQuery("SELECT * FROM card1 WHERE number='zhangsan'");
            rs.next();
            double amountOne = rs.getDouble("amount");
            System.out.println("转账操作之前 zhangsan 的钱款数额:" + amountOne);
            rs = sql.executeQuery("SELECT * FROM card2 WHERE number='xidanShop'");
            rs.next();
            double amountTwo = rs.getDouble("amount");
            System.out.println("转账操作之前 xidanShop 的钱款数额:" + amountTwo);
            amountOne = amountOne - n;
            amountTwo = amountTwo + n;
            sql.executeUpdate(
                    "UPDATE card1 SET amount =" + amountOne + " WHERE number ='zhangsan'");
            sql.executeUpdate(
                    "UPDATE card2 SET amount =" + amountTwo + " WHERE number ='xidanShop'");
            con.commit();
            con.setAutoCommit(true);
            rs = sql.executeQuery("SELECT * FROM card1 WHERE number='zhangsan'");
            rs.next();
            amountOne = rs.getDouble("amount");
            System.out.println("转账操作之后 zhangsan 的钱款数额:" + amountOne);
            rs = sql.executeQuery("SELECT * FROM card2 WHERE number='xidanShop'");
            rs.next();
            amountTwo = rs.getDouble("amount");
            System.out.println("转账操作之后 xidanShop 的钱款数额:" + amountTwo);
            con.close();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException exp) {
            }
            System.out.println(e.toString());
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到