1. 程式人生 > 其它 >Java實驗之元件與事件處理、輸入輸出流

Java實驗之元件與事件處理、輸入輸出流

技術標籤:javaintellij idea

Java實驗之元件與事件處理、輸入輸出流

元件與事件處理

算術測試

編寫一個算術測試小軟體 ,用 來訓練小學生的算術能力。程式有 3個類組成,其中
Teacher對 象 充 當監 視 器 ,負 責 給 出算 術 題 目,並 判 斷 回答 者 的答 案 是 否 正 確 ;
ComputerFrame對 象負責為算術題 目提供檢視,比如使用者可 以通過 ComputerFrame對 象提 供的 GUI界 面看到題 目,並通過該 GUI界 面給出題 目的答案;M擱C1ass是軟體的主類 。
執行結果:在這裡插入圖片描述在這裡插入圖片描述
在這裡插入圖片描述

// Teacher.java
import java.
awt.event.*; import java.util.Random; import javax.swing.*; public class Teacher implements ActionListener{ int numberOne,numberTwo; String operator=""; boolean isRight; Random random;//用於給出隨機數 int maxInterger;//題目中最大的整數 JTextField textOne,textTwo,textResult; JLabel operatorLabel,
message; public Teacher(){ random=new Random(); } public void setMaxInterger(int n){ maxInterger=n; } public void actionPerformed(ActionEvent e){ String str=e.getActionCommand(); if(str.equals("getProblem")){ numberOne=random.
nextInt(maxInterger)+1; numberTwo=random.nextInt(maxInterger)+1; double d=Math.random(); 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]; } }
// ComputerFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComputerFrame extends  JFrame{
    JMenuBar menubar;
    JMenu choiceGrade;//選擇級別的選單
    JMenuItem grade1,grade2;
    JTextField textOne,textTwo,textResult;
    JButton getProblem,giveAnwser;
    JLabel operatorLabel,message;
    Teacher teacherZhang;
    public ComputerFrame(){
        teacherZhang=new Teacher();
        teacherZhang.setMaxInterger(20);
        setLayout(new FlowLayout());
        menubar=new JMenuBar();
        choiceGrade=new JMenu("選擇級別");
        grade1=new JMenuItem("幼兒級別");
        grade2=new JMenuItem("兒童級別");
        grade1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                teacherZhang.setMaxInterger(10);
            }
        });
        grade2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                teacherZhang.setMaxInterger(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);
    }
}

// Main.java
public class Main {

    public static void main(String[] args) {
        ComputerFrame frame;
        frame=new ComputerFrame();
        frame.setTitle("算術測試");
        frame.setBounds(100,100,650,180);

    }
}

輸入輸出流

分析成績單

現在有如下格式的成績單 (文字格式)score.txt:
姓名:張 三,數 學72分 ,物理67分 ,英語70分 .
姓名:李 四,數 學92分 ,物理98分 ,英語88分 .
姓名:周 五,數 學68分 ,物理80分 ,英語77分 .
要求按行讀入取成績單,並在該行的後面尾加上該同學的總成績,然後再將該行寫入 到一個名字為 socreAnalysis. txt的檔案中。
執行結果:
在這裡插入圖片描述

// 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;
    }
}
// Main.java
import java.io.*;
import java.util.*;
public class Main {

    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 bufferedWrite=new BufferedWriter(out);
            Reader in=new FileReader(fRead);
            BufferedReader bufferedRead=new BufferedReader(in);
            String str=null;
            while ((str=bufferedRead.readLine())!=null){
                double totalScore= Fenxi.getTotalScore(str);
                str=str+"總分"+totalScore;
                System.out.println(str);
                bufferedWrite.write(str);
                bufferedWrite.newLine();
            }
        }
        catch (IOException e){
            System.out.println(e.toString());
        }
    }
}

統計英文單詞

使用 scamer類和正則表示式統計一篇英文中的單詞,要求如下:
·一共出現了多少個單詞。
·有多少個互不相同的單詞。
·按單詞出現頻率大小輸出單詞。
執行效果
在這裡插入圖片描述

// 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;
    public 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());
        }
    }
    public 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;
    }
}
// Main.java
import java.util.*;
public class Main {

    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);
                    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);
        }
    }
}
// english.txt
are are are are students students students students We We you Goods