測試題解答

1.編寫一個程序,幫助小學(xué)生學(xué)習(xí)乘法表,利用Math.random產(chǎn)生兩個一位正整數(shù),該程序應(yīng)在控制臺中顯示一個如下的問題:

6*7等于多少?

學(xué)生應(yīng)在文本字段中輸入答案,在程序中檢查文本答案,如果答案正確,則在控制臺中輸出字符串“非常好!”然后提問另一個乘法問題。如果答錯了,則在控制臺中繪制字符串“錯,請重試”然后讓學(xué)生反復(fù)練習(xí)同樣的問題直到回答正確位置,應(yīng)當(dāng)使用一個單獨方法來產(chǎn)生每個新問題。當(dāng)程序開始運行時,如果每次用戶回答正確,則應(yīng)調(diào)用該方法一次。輸入-1代表退出.

public class Question {

    public static int askQuestion()
    {
        //產(chǎn)生2個10以內(nèi)隨機整數(shù)(乘數(shù)和被乘數(shù))
        int a = (int)(Math.random() * 10);
        Random random = new Random();
        int b = random.nextInt(10);
        System.out.println(a+"*"+b+"等于多少?");
        return a*b;
    }

    public static void main(String[] args) {

         Scanner scanner = new Scanner(System.in);
        int answer = askQuestion();//答案
        while (true)
        {
            System.out.println("輸入-1退出程序");

            int user_answer = scanner.nextInt();
            if(user_answer == -1)
            {
                break;
            }

            if(answer == user_answer)
            {
                System.out.println("非常好");
                answer = askQuestion();//答案
            }
            else//打錯了,需要重新出剛才那道題
            {
                System.out.println("錯,請重試");
            }

        }

        System.out.println("程序退出");
    }
}

2.計算機在教育中的應(yīng)用稱之為計算機輔助教學(xué)(CAI)。在開發(fā)CAI環(huán)境中遇到一個問題就是學(xué)生容易疲勞,可通過變換計算機的對話來保持學(xué)生的注意力,從而消除疲勞,修改練習(xí)1中的程序,為每個正確和不正確的答案打印各種評語,對正確的答案的評語如下所示:
Very good!
Excellent!
Nice work!
Keep up the good work!
對不正確的評語如下所以:
No.Pleasa try again.
Wrong.Try once more.
Don't give up!
Nn.keep trying.
利用隨機產(chǎn)生器來選擇1到4中的一個數(shù),從而給出對于每個答案一個恰當(dāng)評語,在paint方法中利用一個switch結(jié)構(gòu)發(fā)出評語。

package com.company;



import java.util.Random;
import java.util.Scanner;

/**
 * Created by ttc on 2018/1/2.
 */
//1.編寫一個程序,幫助小學(xué)生學(xué)習(xí)乘法表,利用Math.random產(chǎn)生兩個一位正整數(shù),
該程序應(yīng)在控制臺中顯示一個如下的問題:
//
//        6*7等于多少?
//
//        學(xué)生應(yīng)在文本字段中輸入答案,在程序中檢查文本答案,如果答案正確,則在控制臺中輸出字符串“非常好!”
//        然后提問另一個乘法問題。如果答錯了,則在控制臺中繪制字符串“錯,請重試”然后讓學(xué)生反復(fù)練習(xí)同樣的問題直到回答正確位置,
//        應(yīng)當(dāng)使用一個單獨方法來產(chǎn)生每個新問題。當(dāng)程序開始運行時,如果每次用戶回答正確,則應(yīng)調(diào)用該方法一次。輸入-1代表退出.
//Very good!非常好
//        Excellent!特別好
//        Nice work!做的好
//        Keep up the good work! 做的好,繼續(xù)保持
//        對不正確的評語如下所以:
//        No.Please try again. 錯,請重試
//        Wrong.Try once more. 錯,再試試
//        Don't give up!        別放棄
//        Nn.keep trying.       保持嘗試
//        利用隨機產(chǎn)生器來選擇1到4中的一個數(shù),從而給出對于每個答案一個恰當(dāng)評語。
public class Question {

    static String[] good = {"非常好","特別好","做的好","做的好,繼續(xù)保持"};
    static String[] error = {"錯,請重試","錯,再試試","別放棄","保持嘗試"};

    public static int askQuestion()
    {
        //產(chǎn)生2個10以內(nèi)隨機整數(shù)(乘數(shù)和被乘數(shù))
        int a = (int)(Math.random() * 9)+1;
        Random random = new Random();
        int b = random.nextInt(9)+1;
        System.out.println(a+"*"+b+"等于多少?");
        return a*b;
    }

    public static void main(String[] args) {

         Scanner scanner = new Scanner(System.in);
        int answer = askQuestion();//答案
        while (true)
        {
            System.out.println("輸入-1退出程序");

            int user_answer = scanner.nextInt();
            if(user_answer == -1)
            {
                break;
            }

            if(answer == user_answer)
            {
                Random random = new Random();
                int index = random.nextInt(4);
                System.out.println(good[index]);
                answer = askQuestion();//答案
            }
            else//打錯了,需要重新出剛才那道題
            {

                Random random = new Random();
                int index = random.nextInt(4);
                System.out.println(error[index]);
            }

        }

        System.out.println("程序退出");
    }
}
  1. 編寫一個程序,按照如下規(guī)則玩“猜數(shù)游戲”:在程序中,通過選擇一個1——1000的整數(shù)之間隨機數(shù)來確定要猜的數(shù)。程序在一個文本字段 旁顯示提示:

猜一個1-1000之間的數(shù)

玩家在文本字段中輸入第一個數(shù)并按下回車鍵。如果玩家猜錯了,程序應(yīng)當(dāng)在狀態(tài)欄中顯示“太大了,再試”或者“太小了再試”,幫助玩家“接近”正確答案并清除文本字段,以便用用戶能輸入下一個猜測的數(shù)。當(dāng)用戶輸入了正確答案后,就顯示“祝賀你,猜對了”,在控制臺中清除文本字段以便用戶可以再次進(jìn)行游戲。提示:這個問題種使用查找技術(shù)稱為二分查找(binary search)。

ublic class GuessNumber {
    public static void main(String[] args) {
        Random random = new Random();
        int guessnum = random.nextInt(1000)+1;//生成一個隨機數(shù),讓用戶猜

//        System.out.println(guessnum);
        int guessCount = 0;//記錄用戶猜了多少次
        Scanner scanner = new Scanner(System.in);
        System.out.println("請猜數(shù)");
        int input = scanner.nextInt();//用戶第一次輸入答案
        guessCount++;
        while (input != guessnum)
        {
            if(input > guessnum)
            {
                System.out.println("太大了");
            }
            else
            {
                System.out.println("太小了");
            }
            guessCount++;
            System.out.println("請猜數(shù)");
            input = scanner.nextInt();//讓用戶再次輸入答案
        }

        System.out.println("程序退出,一共用了"+ guessCount + "次");

    }
}

4.(航空訂票系統(tǒng))一家小型航空公司剛購買一臺計算機,用于其最新的自動訂票系統(tǒng),要求讀者編寫新的程序,為該公司唯一一架飛機(運量:10)的每次飛行安排座位,程序應(yīng)當(dāng)顯示下列選項:
Please type 1 for "smoking"(吸煙區(qū)請安1)
Please type 2 for "nonsmoking"(無煙區(qū)請安2)
如果沒人按下1,那么程序應(yīng)當(dāng)在吸煙艙(1——5)為其分配一個座位。如果某人按下2,那么程序應(yīng)當(dāng)在無煙艙為期分配一個座位(6——10)。在程序中應(yīng)打印出一張登記卡,以表明此人的座號以及他在飛機的吸煙艙還是無煙艙。用一個單下標(biāo)數(shù)組描述飛機的訂票情況,將所有的數(shù)組元素初始化為0,表明所有座位都是空的。在分配一個座位后,設(shè)置數(shù)組的相應(yīng)元素為1,則該座位不能再分配,
程序中當(dāng)然不應(yīng)分配已分配的座位。單吸煙艙客滿后程序應(yīng)當(dāng)詢問此人是否接受安排的無煙區(qū),反之亦然。如果回答肯定,那么應(yīng)當(dāng)進(jìn)行適當(dāng)?shù)淖话才拧H绻卮鸱穸?,那么打印消息“Next flight leaves in 3 hours.”(下次航班三小時后起飛)。

package com.company;

import java.util.Scanner;

/**
 * Created by ttc on 2018/1/2.
 */
public class FlyOrderTicket {

    public static void main(String[] args) {

        int[] seats = new int[10];//代表10個空閑座位,其中1-5是吸煙區(qū),6-10是無煙區(qū)
        Scanner scanner = new Scanner(System.in);

        while (true)
        {
            System.out.println("吸煙區(qū)請安1,無煙區(qū)請安2,退出按-1");
            int command = scanner.nextInt();
            if(command == -1)
            {
                break;
            }
            else if(command == 1)//在吸煙區(qū)給用戶分配一個座位
            {
                int i;
                for(i = 0; i < 5; i++)
                {
                    //考察座位是否已經(jīng)被分配出去了
                    if(seats[i] == 0)//當(dāng)前座位可以分配
                    {
                        seats[i] = 1;//分配出去了該座位
                        System.out.println("你的座號是"+(i+1) + "在吸煙區(qū)");//打印登記卡
                        break;
                    }
                }

                if(i == 5)//沒有在吸煙區(qū)找到空余座位
                {
                    System.out.println("吸煙區(qū)無座位了,是否接受無煙區(qū)的座位?");
                    String answer = scanner.next();
                    if(answer.equals("是"))//在無煙區(qū)分配座位
                    {
                        int j;
                        for(j = 5; j < 10; j++)
                        {
                            //考察座位是否已經(jīng)被分配出去了
                            if(seats[j] == 0)//當(dāng)前座位可以分配
                            {
                                seats[j] = 1;//分配出去了該座位
                                System.out.println("你的座號是"+(j+1) + "在無煙區(qū)");//打印登記卡
                                break;
                            }
                        }

                        if(j==10)//無煙區(qū)也沒有座位了
                        {
                            System.out.println("下次航班三小時后起飛");
                        }

                    }
                    else
                    {
                        System.out.println("下次航班三小時后起飛");
                    }
                }

            }
            else if(command == 2)//在無煙區(qū)分配座位
            {
                int j;
                for(j = 5; j < 10; j++)
                {
                    //考察座位是否已經(jīng)被分配出去了
                    if(seats[j] == 0)//當(dāng)前座位可以分配
                    {
                        seats[j] = 1;//分配出去了該座位
                        System.out.println("你的座號是"+(j+1) + "在無煙區(qū)");//打印登記卡
                        break;
                    }
                }
                if(j==10)//無煙區(qū)沒有座位了
                {
                    System.out.println("無煙區(qū)無座位了,是否接受吸煙區(qū)的座位?");
                    String answer = scanner.next();
                    if (answer.equals("是"))//在無煙區(qū)分配座位
                    {
                        int i;
                        for (i = 0; i < 5; i++) {
                            //考察座位是否已經(jīng)被分配出去了
                            if (seats[i] == 0)//當(dāng)前座位可以分配
                            {
                                seats[i] = 1;//分配出去了該座位
                                System.out.println("你的座號是" + (i + 1) + "在吸煙區(qū)");//打印登記卡
                                break;
                            }
                        }

                        if (i == 5)//吸煙區(qū)也沒有座位了
                        {
                            System.out.println("下次航班三小時后起飛");
                        }
                    }
                }

            }

        }

        System.out.println("謝謝使用");

    }
}
第二種算法簡單代碼
public class FlyOrderTicket {
    static int[] seats = new int[10];//代表10個空閑座位,其中1-5是吸煙區(qū),6-10是無煙區(qū)


    public static int allocSeats(int start, int end)
    {
        String strArea = "吸煙區(qū)";
        if(end == 10)
        {
            strArea = "無煙區(qū)";
        }
        int i;
        for(i = start; i < end; i++)
        {
            //考察座位是否已經(jīng)被分配出去了
            if(seats[i] == 0)//當(dāng)前座位可以分配
            {
                seats[i] = 1;//分配出去了該座位
                System.out.println("你的座號是"+(i+1) + "在" + strArea);//打印登記卡
                break;
            }
        }
        return i;
    }

    public static void main(String[] args) {


        Scanner scanner = new Scanner(System.in);

        while (true)
        {
            System.out.println("吸煙區(qū)請安1,無煙區(qū)請安2,退出按-1");
            int command = scanner.nextInt();
            if(command == -1)
            {
                break;
            }
            else if(command == 1)//在吸煙區(qū)給用戶分配一個座位
            {
                int i = allocSeats(0,5);

                if(i == 5)//沒有在吸煙區(qū)找到空余座位
                {
                    System.out.println("吸煙區(qū)無座位了,是否接受無煙區(qū)的座位?");
                    String answer = scanner.next();
                    if(answer.equals("是"))//在無煙區(qū)分配座位
                    {
                        int j = allocSeats(5,10);


                        if(j==10)//無煙區(qū)也沒有座位了
                        {
                            System.out.println("下次航班三小時后起飛");
                        }

                    }
                    else
                    {
                        System.out.println("下次航班三小時后起飛");
                    }
                }

            }
            else if(command == 2)//在無煙區(qū)分配座位
            {
                int j = allocSeats(5,10);

                if(j==10)//無煙區(qū)沒有座位了
                {
                    System.out.println("無煙區(qū)無座位了,是否接受吸煙區(qū)的座位?");
                    String answer = scanner.next();
                    if (answer.equals("是"))//在無煙區(qū)分配座位
                    {
                        int i = allocSeats(0,5);

                        if (i == 5)//吸煙區(qū)也沒有座位了
                        {
                            System.out.println("下次航班三小時后起飛");
                        }
                    }
                }

            }

        }

        System.out.println("謝謝使用");

    }
}

5.某個公司采用公用電話傳遞數(shù)據(jù)信息,數(shù)據(jù)是小于8位的整數(shù),為了確保安全,5698234 --》 4328965 ---》9873410 -- 》 0873419
在傳遞過程中需要加密,加密規(guī)則如下:
首先將數(shù)據(jù)倒序,然后將每位數(shù)字都加上5,再用和除以10的余數(shù)代替該數(shù)字,
最后將第一位和最后一位數(shù)字交換。 請任意給定一個小于8位的整數(shù),
然后,把加密后的結(jié)果在控制臺打印出來。

package com;

import java.util.Scanner;
/**
 * Created by ttc on 2018/1/2.
 */
public class JiaMi {
    public static void main(String[] args) {
        int index = 0; //數(shù)組當(dāng)前的下標(biāo)
        int[] array = new int[8];
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入要加密的數(shù)");
        int num = scanner.nextInt();//--》 4328965
        //將數(shù)倒序,保存到數(shù)組中
        while (num != 0)
        {
            array[index] = num % 10;
            index++;
            num = num / 10;
        }

        for(int i = 0; i < index; i++)
        {
            array[i] = (array[i] + 5) % 10; //每位數(shù)字都加上5,再用和除以10的余數(shù)代替該數(shù)字
        }

         //最后將第一位和最后一位數(shù)字交換
        int temp = array[0];
        array[0] = array[index - 1];
        array[index - 1] = temp;

        for(int i = 0; i < index; i++)
        {
            System.out.print(array[i]);
        }

        return;
    }
}

6.工資支付系統(tǒng)
定義一個Employee抽象基類(name)
公司有以下幾種員工:
開發(fā)人員:工資計算方式,每月固定工資
銷售人員:底薪+提成
硬件工程師:生產(chǎn)零件,每個50元
小時工:按工作時間付工資,每小時30元
主類(測試類)
創(chuàng)建不同類型的6名員工對象,計算他們應(yīng)付的月工資。
1.開發(fā)人員

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
//開發(fā)人員
public class Developer extends Employee{

    private int salary;

    public Developer(String name, int salary)
    {
        super(name);
        this.salary = salary;

    }

    @Override//方法重寫注解
    protected int paySalary() {
        return salary;
    }
}

2.老板

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
public class Boss extends Employee {

    public Boss(String name)
    {
        super(name);
    }

    @Override
    protected int paySalary() {
        return 200000;
    }
}

3.抽象基類

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
public abstract class Employee {

    private String name;

    public Employee(String name)
    {
        this.name = "@" + name + "@" ;
    }
    protected abstract int paySalary();
}

4.硬件工程師

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
//硬件工程師
public class HardwareEngineer extends Employee {
    private int productCount;//每月生產(chǎn)的零件數(shù)量

    public HardwareEngineer(String name, int productCount)
    {
        super(name);
        this.productCount = productCount;
    }

    @Override
    protected int paySalary() {
        return 50*productCount;
    }
}

5.小時工

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
//小時工
public class HourlyWorker extends Employee{
    private int hours;//這個月工作了多少小時

    public HourlyWorker(String name, int hours)
    {
        super(name);
        this.hours = hours;
    }
    @Override
    protected int paySalary() {
        return 30*hours;
    }
}

6.測試類

package duotai;

public class Main {

    public static void main(String[] args) {
    // write your code here

        Employee[] employees = new Employee[6];
        employees[0] = new Developer("張二",5000);
        employees[1] = new Developer("張三",5000);
        employees[2] = new SaleMan("李四", 2000, 500);
        employees[3] = new HardwareEngineer("王五", 200);
        employees[4] = new HourlyWorker("馮六",200);
        employees[5] = new Boss("趙本山");

        //計算總工資
        int total = 0;
        for(int i = 0; i < employees.length; i++)
        {
            total += employees[i].paySalary();
        }
        System.out.println("總共需要支付" + total);
    }
}

7.銷售人員

package duotai;

/**
 * Created by ttc on 2018/1/4.
 */
//銷售人員
public class SaleMan extends Employee{
    private int salary;
    private int comm;//提成

    public SaleMan(String name, int salary, int comm)
    {
        super(name);
        this.salary = salary;
        this.comm = comm;

    }
    @Override
    protected int paySalary() {
        return salary + comm;
    }
}

7.編寫一個applet,將英語單詞編碼成pig Latin。pig Latin是一種常用于娛樂編碼的語言形式,有許多方法用于組成pig Latin,簡單來說可以使用下列算法:
為了從英語詞組生成pig Latin,可以使用StringTokenizer類的對象來將詞組分成單詞。為了將每個英語單詞翻譯成一個pig Latin,可以將英語單詞的第一個字母放在單詞末尾并加上字母“ay”。這樣單詞“jump”變成了“umpjay”,單詞“the”變成了“hetay”,單詞“computer”變成了“omputercay”,單詞之間的空格仍為空格。這里做如下決定:英語詞組的單詞有空格分開,沒有標(biāo)點符號,所有的單詞有兩個或更多的字母。應(yīng)當(dāng)使用printLatinWord方法顯示每個單詞,每個由nextToken返回的語法標(biāo)記都傳遞給printLatinWord方法來打印pigLatin。該程序應(yīng)讀入用戶輸入的語句,并在文本區(qū)域中顯示所有已轉(zhuǎn)換的語句。

package lakei;

import java.util.Scanner;

/**
 * Created by ttc on 18-1-5.
 */
public class pigLatin {
    public static void main(String[] args) {
        System.out.println("請輸入一句英語");
        Scanner scanner = new Scanner(System.in);
        String strSentence = scanner.nextLine();
       // System.out.println(strSentence);


        String[] strWords = strSentence.split(" ");// 雙引號里面"加空格"
        for (int i = 0; i < strWords.length; i++) {
            char c = strWords[i].charAt(0);
            String strLast = strWords[i].substring(1);

            strWords[i] = strLast + c + "ay";

        }
        for (int i = 0; i < strWords.length; i++) {
            System.out.print(strWords[i]);
        }
    }

8.編寫一個applet,利用隨機數(shù)產(chǎn)生器來創(chuàng)建語句,使用稱為article、noun、verb和preposition的4個數(shù)組,按照下列順序從每個數(shù)組中選取隨機的單詞來創(chuàng)建一條語句:article、noun、verb、preposition、article、和noun。選出每個單詞后,將其連接到語句中的前一個單詞之后,單詞之間應(yīng)當(dāng)由空格分開。輸出最后的語句時,該語句應(yīng)當(dāng)以大寫字母開頭并以句點結(jié)尾。程序應(yīng)當(dāng)生成2語句并輸出到一個文本區(qū)域中。
article數(shù)組應(yīng)該包含冠詞:the、a、one、some、any;

noun:數(shù)組應(yīng)該包含名詞:boy、girl、dog、town、car;

verb:數(shù)組應(yīng)該包含動詞:drove、jumped、ran、walked、skipped;

preposition:數(shù)組應(yīng)該包含介詞:to、from、over、under、on;

編寫完上面的程序后,修改該程序以生成包含這幾個句子的小故事

package aishuishui;

import java.util.Random;

//        編寫一個程序,利用隨機數(shù)產(chǎn)生器來創(chuàng)建語句,使用稱為article、noun、verb和preposition的4個數(shù)組,
// 按照下列順序從每個數(shù)組中選取隨機的單詞來創(chuàng)建一條語句:article、noun、verb、article、和noun。
// 選出每個單詞后,將其連接到語句中的前一個單詞之后,單詞之間應(yīng)當(dāng)由空格分開。
// 輸出最后的語句時,該語句應(yīng)當(dāng)以大寫字母開頭并以句點結(jié)尾。程序應(yīng)當(dāng)生成2語句并輸出到一個文本區(qū)域中。
//
//        article數(shù)組應(yīng)該包含冠詞:the、a、one、some、any;
//
//        noun:數(shù)組應(yīng)該包含名詞:boy、girl、dog、town、car;
//
//        verb:數(shù)組應(yīng)該包含動詞:drove、jumped、ran、walked、skipped;
//        


//
//        One boy ran a dog preposition.
public class Main {

    public static String firstCharToUpper(String str)
    {
        char first = str.toUpperCase().charAt(0);//H
        String strLast = str.substring(1);
        String strFinal = first + strLast;
        return strFinal;
    }
    public static void main(String[] args) {



    // write your code here
        String[] article = {"the","two","three","some","any"};
        String[] noun={"男孩","女孩","狗","城鎮(zhèn)","汽車"};
        String[] verb={"駕駛","跳","跑","走","親"};

        //定義一個字符串?dāng)?shù)組來保存生成的句子
        String[] sentence = new String[5];
        int index = 0;//句子中下一個要保存的單詞

        //從article隨機選出一個單詞
        Random random = new Random();
        int nIndex = random.nextInt(5);
        sentence[index] = article[nIndex];
        index++;

        //從noun隨機選出一個單詞
        nIndex = random.nextInt(5);
        sentence[index] = noun[nIndex];
        index++;
        //從noun隨機選出一個單詞
        nIndex = random.nextInt(5);
        sentence[index] = verb[nIndex];
        index++;

        //從article隨機選出一個單詞
        nIndex = random.nextInt(5);
        sentence[index] = article[nIndex];
        index++;
        //從noun隨機選出一個單詞
        nIndex = random.nextInt(5);
        sentence[index] = noun[nIndex];

        String strSentence = "";
        for(int i = 0; i <sentence.length; i++)
        {
            strSentence = strSentence + sentence[i];
        }

        strSentence = firstCharToUpper(strSentence);
        System.out.println(strSentence + "。");
    }
}

9.統(tǒng)計單詞次數(shù)
一個文件(d:/article.txt)中,保存著以下一段文章,單詞間以空格分隔。

Today I can complain because the weather is rainy or I can be thankful that the grass is getting watered for free Today I can fell sad that I don't have more money or I can be glad that my finances encourage me to plan my purchases wisely and guide me away from waste

要求統(tǒng)計該文章中各個單詞出現(xiàn)的次數(shù),并且按次數(shù)出現(xiàn)多少從多到少排序,將結(jié)果輸出至d:/result.txt中。

I-----5
can-----4
that-----3
be-----2
me-----2
or-----2
is-----2
my-----2
the-----2
Today-----2
away-----1
thankful-----1
don't-----1
for-----1
getting-----1
fell-----1
rainy-----1
encourage-----1
grass-----1
and-----1
sad-----1
weather-----1
have-----1
from-----1
because-----1
free-----1
plan-----1
guide-----1
waste-----1
purchases-----1
more-----1
watered-----1
complain-----1
money-----1
glad-----1
to-----1
finances-----1
wisely-----1

代碼:主類

package com.company;

import java.io.*;
import java.util.*;

/**
 * Created by ttc on 2018/1/19.
 */
public class FileWordCount {
    public static void main(String[] args) throws IOException {
        //讀取文件中的文章
        FileReader fileReader = new FileReader("d:/article.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String strContent = bufferedReader.readLine();

        StringBuilder stringBuilder = new StringBuilder();
        while (strContent != null)//還有未曾讀完的內(nèi)容
        {
            stringBuilder.append(strContent);
            //繼續(xù)讀取下一行
            strContent = bufferedReader.readLine();
        }
        System.out.println(stringBuilder.toString());

        //用空格分隔,打破成字符串?dāng)?shù)組
        String[] words = stringBuilder.toString().split(" ");
        System.out.println(words);

        //定義一個map結(jié)構(gòu),key保存單詞,值保存單詞出現(xiàn)的次數(shù)
        Map<String,Integer> word2Counts = new HashMap<>();

        //將單詞從數(shù)組結(jié)構(gòu),轉(zhuǎn)換為map結(jié)構(gòu)
        for(String word : words)
        {
            //考察每個單詞,如果單詞出現(xiàn)在Map的key中,取出對應(yīng)的值(也就是該單詞已經(jīng)出現(xiàn)的次數(shù)),
            //將其加1,然后放回map
            if(word2Counts.containsKey(word))
            {
                int count = word2Counts.get(word);
                count++;
                word2Counts.put(word,count);
            }
            else//否則,意味著該單詞首次出現(xiàn),那么將該單詞放入map中,并且將次數(shù)設(shè)置為1
            {
                word2Counts.put(word,1);
            }

        }

        FileWriter fileWriter = new FileWriter("d:/result.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


        //將單詞信息,從map結(jié)構(gòu)轉(zhuǎn)換到list結(jié)構(gòu)
        List<WordInfo> wordInfoList = new ArrayList<WordInfo>();

        for(Map.Entry<String, Integer> entry : word2Counts.entrySet())
        {
            WordInfo wordInfo = new WordInfo();
            wordInfo.setWord(entry.getKey());
            wordInfo.setCount(entry.getValue());
            wordInfoList.add(wordInfo);
        }

        Collections.sort(wordInfoList);

        for(WordInfo wordInfo : wordInfoList)
        {
            bufferedWriter.write(wordInfo.getWord()+ "-----");
            bufferedWriter.write(String.valueOf(wordInfo.getCount()));
            bufferedWriter.newLine();
        }

        bufferedWriter.flush();
        fileReader.close();
        fileWriter.close();
        bufferedReader.close();
        bufferedWriter.close();

    }
}

副類代碼

package com.company;

/**
 * Created by ttc on 2018/1/19.
 */
public class WordInfo implements Comparable {
    private String word;
    private int count;

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }


    @Override
    public int compareTo(Object o) {
//        System.out.println("compareTo");
        WordInfo wordInfo = (WordInfo)o;
        return wordInfo.getCount()-this.count;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,734評論 18 399
  • 3.2 函數(shù)和所生成的過程 來源:3.2 Functions and the Processes They G...
    布客飛龍閱讀 1,154評論 0 37
  • 摘要 越來越多的公司需要分析每天產(chǎn)生的海量數(shù)據(jù)。也產(chǎn)生了很多平行數(shù)據(jù)庫產(chǎn)品,然而它們的可擴展性的代價很高。 引言 ...
    哲人善思閱讀 866評論 0 3
  • 這篇文章是前段時間寫的,趁著明天的母親節(jié)詳盡的添加了些。母親節(jié),街道上,商場里,各種網(wǎng)絡(luò)平臺上,都是對母親的歌頌。...
    云上之人閱讀 464評論 0 0
  • #The Real-life MBA#第1天 #海納百川讀書會# 樊登讀書會企業(yè)版的內(nèi)容傳遞 關(guān)鍵詞:2個多數(shù)人信...
    敬恒教練閱讀 375評論 0 0

友情鏈接更多精彩內(nèi)容