首页 > 技术文章 > Java零基础系列教程18java练习题题解

songboriceboy 2020-10-01 13:10 原文

配套视频教程

本文B站配套视频教程

1.编写一个程序,帮助小学生学习乘法表,利用Math.random产生两个一位正整数,该程序应在控制台中显示一个如下的问题:

6*7等于多少?

学生应在文本字段中输入答案,在程序中检查文本答案,如果答案正确,则在控制台中输出字符串“非常好!”然后提问另一个乘法问题。如果答错了,则在控制台中绘制字符串“错,请重试”然后让学生反复练习同样的问题直到回答正确位置,应当使用一个单独方法来产生每个新问题。当程序开始运行时,如果每次用户回答正确,则应调用该方法一次。输入-1代表退出.

public class Question {

    public static int askQuestion()
    {
        //产生2个10以内随机整数(乘数和被乘数)
        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)
            {
                System.out.println("非常好");
                answer = askQuestion();//答案
            }
            else//打错了,需要重新出刚才那道题
            {
                System.out.println("错,请重试");
            }

        }

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

2.计算机在教育中的应用称之为计算机辅助教学(CAI)。在开发CAI环境中遇到一个问题就是学生容易疲劳,可通过变换计算机的对话来保持学生的

注意力,从而消除疲劳,修改练习1中的程序,为每个正确和不正确的答案打印各种评语,对正确的答案的评语如下所示:
Very good!非常好
Excellent!特别好
Nice work!做的好
Keep up the good work! 做的好,继续保持
对不正确的评语如下所以:
No.Please try again. 错,请重试
Wrong.Try once more. 错,再试试
Don't give up! 别放弃
Nn.keep trying. 保持尝试
利用随机产生器来选择1到4中的一个数,从而给出对于每个答案一个恰当评语。

public class Question {

    static String[] good = {"非常好","特别好","做的好","做的好,继续保持"};
    static String[] error = {"错,请重试","错,再试试","别放弃","保持尝试"};

    public static int askQuestion()
    {
        //产生2个10以内随机整数(乘数和被乘数)
        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. 编写一个程序,按照如下规则玩“猜数游戏”:在程序中,通过选择一个1——1000的整数之间随机数来确定要猜的数。程序在一个文本字段旁显示提示:

猜一个1-1000之间的数

玩家在文本字段中输入第一个数并按下回车键。如果玩家猜错了,程序应当在状态栏中显示“太大了,再试”或者“太小了再试”,帮助玩家“接近”正确答案并清除文本字段,以便用用户能输入下一个猜测的数。当用户输入了正确答案后,就显示“祝贺你,猜对了”,在控制台中清除文本字段以便用户可以再次进行游戏。提示:这个问题种使用查找技术称为二分查找(binary search)。

public class GuessNumber {
    public static void main(String[] args) {
        Random random = new Random();
        int guessnum = random.nextInt(1000)+1;//生成一个随机数,让用户猜

//        System.out.println(guessnum);
        int guessCount = 0;//记录用户猜了多少次
        Scanner scanner = new Scanner(System.in);
        System.out.println("请猜数");
        int input = scanner.nextInt();//用户第一次输入答案
        guessCount++;
        while (input != guessnum)
        {
            if(input > guessnum)
            {
                System.out.println("太大了");
            }
            else
            {
                System.out.println("太小了");
            }
            guessCount++;
            System.out.println("请猜数");
            input = scanner.nextInt();//让用户再次输入答案
        }

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

    }
}

4.(航空订票系统)一家小型航空公司刚购买一台计算机,用于其最新的自动订票系统,要求编写新的程序,为该公司唯一一架飞机(运量:10

)的每次飞行安排座位,程序应当显示下列选项:
Please type 1 for "smoking"(吸烟区请安1)
Please type 2 for "nonsmoking"(无烟区请安2)
如果某人按下1,那么程序应当在吸烟舱(1——5)为其分配一个座位。如果某人按下2,那么程序应当在无烟舱为其分配一个座位(6——10)。在

程序中应打印出一张登记卡,以表明此人的座号以及他在飞机的吸烟舱还是无烟舱。用一个单下标数组描述飞机的订票情况,将所有的数组元素初始

化为0,表明所有座位都是空的。在分配一个座位后,设置数组的相应元素为1,则该座位不能再分配,
程序中当然不应分配已分配的座位。当吸烟舱客满后程序应当询问此人是否接受安排的无烟区,反之亦然。如果回答肯定,那么应当进行适当的座位

安排。如果回答否定,那么打印消息“Next flight leaves in 3 hours.”(下次航班三小时后起飞)。

public class FlyOrderTicket {

    
    
    public static void main(String[] args) {

        int[] seats = new int[10];//代表10个空闲座位,其中1-5是吸烟区,6-10是无烟区
        Scanner scanner = new Scanner(System.in);

        while (true)
        {
            System.out.println("吸烟区请安1,无烟区请安2,退出按-1");
            int command = scanner.nextInt();
            if(command == -1)
            {
                break;
            }
            else if(command == 1)//在吸烟区给用户分配一个座位
            {
                int i;
                for(i = 0; i < 5; i++)
                {
                    //考察座位是否已经被分配出去了
                    if(seats[i] == 0)//当前座位可以分配
                    {
                        seats[i] = 1;//分配出去了该座位
                        System.out.println("你的座号是"+(i+1) + "在吸烟区");//打印登记卡
                        break;
                    }
                }

                if(i == 5)//没有在吸烟区找到空余座位
                {
                    System.out.println("吸烟区无座位了,是否接受无烟区的座位?");
                    String answer = scanner.next();
                    if(answer.equals("是"))//在无烟区分配座位
                    {
                        int j;
                        for(j = 5; j < 10; j++)
                        {
                            //考察座位是否已经被分配出去了
                            if(seats[j] == 0)//当前座位可以分配
                            {
                                seats[j] = 1;//分配出去了该座位
                                System.out.println("你的座号是"+(j+1) + "在无烟区");//打印登记卡
                                break;
                            }
                        }

                        if(j==10)//无烟区也没有座位了
                        {
                            System.out.println("下次航班三小时后起飞");
                        }

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

            }
            else if(command == 2)//在无烟区分配座位
            {
                int j;
                for(j = 5; j < 10; j++)
                {
                    //考察座位是否已经被分配出去了
                    if(seats[j] == 0)//当前座位可以分配
                    {
                        seats[j] = 1;//分配出去了该座位
                        System.out.println("你的座号是"+(j+1) + "在无烟区");//打印登记卡
                        break;
                    }
                }
                if(j==10)//无烟区没有座位了
                {
                    System.out.println("无烟区无座位了,是否接受吸烟区的座位?");
                    String answer = scanner.next();
                    if (answer.equals("是"))//在无烟区分配座位
                    {
                        int i;
                        for (i = 0; i < 5; i++) {
                            //考察座位是否已经被分配出去了
                            if (seats[i] == 0)//当前座位可以分配
                            {
                                seats[i] = 1;//分配出去了该座位
                                System.out.println("你的座号是" + (i + 1) + "在吸烟区");//打印登记卡
                                break;
                            }
                        }

                        if (i == 5)//吸烟区也没有座位了
                        {
                            System.out.println("下次航班三小时后起飞");
                        }
                    }
                }

            }

        }

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

    }
}

方法提取版

public class FlyOrderTicket {
    static int[] seats = new int[10];//代表10个空闲座位,其中1-5是吸烟区,6-10是无烟区


    public static int allocSeats(int start, int end)
    {
        String strArea = "吸烟区";
        if(end == 10)
        {
            strArea = "无烟区";
        }
        int i;
        for(i = start; i < end; i++)
        {
            //考察座位是否已经被分配出去了
            if(seats[i] == 0)//当前座位可以分配
            {
                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("吸烟区请安1,无烟区请安2,退出按-1");
            int command = scanner.nextInt();
            if(command == -1)
            {
                break;
            }
            else if(command == 1)//在吸烟区给用户分配一个座位
            {
                int i = allocSeats(0,5);

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


                        if(j==10)//无烟区也没有座位了
                        {
                            System.out.println("下次航班三小时后起飞");
                        }

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

            }
            else if(command == 2)//在无烟区分配座位
            {
                int j = allocSeats(5,10);

                if(j==10)//无烟区没有座位了
                {
                    System.out.println("无烟区无座位了,是否接受吸烟区的座位?");
                    String answer = scanner.next();
                    if (answer.equals("是"))//在无烟区分配座位
                    {
                        int i = allocSeats(0,5);

                        if (i == 5)//吸烟区也没有座位了
                        {
                            System.out.println("下次航班三小时后起飞");
                        }
                    }
                }

            }

        }

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

    }
}

  1. 某个公司采用公用电话传递数据信息,数据是小于8位的整数,为了确保安全,5698234 --》 4328965 ---》9873410 -- 》 0873419
    在传递过程中需要加密,加密规则如下:

     首先将数据倒序,然后将每位数字都加上5,再用和除以10的余数代替该数字,
     最后将第一位和最后一位数字交换。 请任意给定一个小于8位的整数,
     然后,把加密后的结果在控制台打印出来。 
    
public class JiaMi {
    public static void main(String[] args) {
        int index = 0; //数组当前的下标
        int[] array = new int[8];
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要加密的数");
        int num = scanner.nextInt();//--》 4328965
        //将数倒序,保存到数组中
        while (num != 0)
        {
            array[index] = num % 10;
            index++;
            num = num / 10;
        }

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

         //最后将第一位和最后一位数字交换
        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 龟兔赛跑

(模拟程序:龟兔赛跑)在这个问题中,我们将再现经典的龟兔赛跑。 程序中使用随机数生成法来开发一个模拟这一著名事件的应用程序。

比赛场地为70个方格,参赛者从“方格1”开始出发,每个方格代表比赛过程中所经过的一个位置。终点为“方格70”。最先到达或者通过“方格70”的参赛者将赢得一桶新鲜的胡萝卜和莴苣。在比赛过程中可能会经过一段很滑的山路,所有参赛者可能会滑倒。

程序中有一只时钟,美妙滴答一次,程序应该根据下列规则来调整动物的位置:

|移动类型|时间百分比|实际移动|

乌龟
|快速走* |50%|向右03格|
|
滑倒** |20%|向左06格|
|慢速走
|30%*|向右01格|

兔兔
|睡觉** |20%|原地不动|
|
大跳** |
20%|向右09格|
|大滑倒
|
10%|向左12格|
|
小跳** |
30%|向右01格|
|小滑倒
|
20%**|向左02格|

使用几个变量来跟踪动物的位置(即1-70号)。在位置1(即起跑线)上启动每个动物。如果动物在方格1前向左滑动,则将的动物移回方格1。

通过产生一个随机数i来生成上表中的百分比,i的范围是1<=i<=10。对于乌龟而言,当1<=i<=5时“快速走”,当6<=i<=7时“打滑”,当8<=i<=10时“慢速走”。
使用类似的方法来移动兔兔。比赛开始时打印以下字符串:

BANG!!!!(砰!)

AND THE'RE OFF!!!(他们出发了!!!)

程序继续执行,时钟每滴答一次(即每循环一次),就打印70号方格位置的一条线,其中乌龟的位置用T表示,兔兔的位置用H表示。偶尔,竞赛者每会挤到同一个格子上。此时,乌龟会咬兔兔,程序要在这个位置上打印“OUCH!!!”(哎呦!!!)。所有不是T、H或OUCH!!!(僵局情形)的地方都用空格代替。

打印出每行之后,确定每个动物是否到达或者穿过了70号方格。如果有,这打印出胜者并终止模拟程序。如果是乌龟胜利了,则打印“TORTOISE WINS!!!YAY!!!”,如果是兔兔获胜了,则打印“Hare wins.Yuch”。如果两个动物在同一时刻打成平手,那么应当表扬乌龟(因其处于劣势),或者打印“It's a tie”。如果没有动物获胜,就再执行一遍循环来模拟时钟的下个时刻。

package com.company;

import java.util.Random;

public class Main {
    //赛道
    static char[] road = new char[70];
    //乌龟当前位置
    static int tPosition = 0;
    //兔子当前位置
    static int hPosition = 0;

    //判断乌龟该移动多少步
    //            动物|移动类型|时间百分比|实际移动|
//                    ----------------------------------
//                            乌龟|快速走* |***50%****|向右03格|
//    |*滑倒** |***20%****|向左06格|
//    |慢速走* |***30%****|向右01格|
//                ----------------------------------
    public static void computeTortoiseNewPosition(int num)
    {

        if (num >= 1 && num <= 5) {
            tPosition += 3;
        } else if (num >= 6 && num <= 7) {
            tPosition -= 6;
            if (tPosition < 0) {
                tPosition = 0;
            }
        } else {
            tPosition += 1;
        }
    }
    // //判断兔兔该移动多少步
    //兔兔|*睡觉** |***20%****|原地不动|
//    |*大跳** |***20%****|向右09格|
//    |大滑倒* |***10%****|向左12格|
//    |*小跳** |***30%****|向右01格|
//    |小滑倒* |***20%****|向左02格|
//                ----------------------------------
    public static void computeHareNewPosition(int num)
    {
        if (num >= 1 && num <= 2) {
            hPosition += 0;
        } else if (num >= 3 && num <= 4) {
            hPosition += 9;
        } else if (num == 5) {
            hPosition -= 12;
            if (hPosition < 0) {
                hPosition = 0;
            }
        } else if (num >= 6 && num <= 8) {
            hPosition += 1;
        } else {
            hPosition -= 2;
            if (hPosition < 0) {
                hPosition = 0;
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
	// write your code here

        System.out.println("开跑");
        while (true) {
            //给跑道的每一格赋初始值
            for(int i = 0; i < road.length; i++)
            {
                road[i] = '-';
            }

            //每一次循环(每次时钟滴答),兔子要按规则行走,乌龟也要按规则行走
            Random random = new Random();
            int num = random.nextInt(10) + 1;

            computeTortoiseNewPosition(num);
            computeHareNewPosition(num);

            //判断是否有人到达了终点
            if (tPosition >= 70 || hPosition >= 70)
            {
                break;//胜负已分
            }

            road[tPosition] = '龟';
            road[hPosition] = '兔';

            if(tPosition == hPosition)//龟和兔重合,也即在数组的同一格上
            {
                road[tPosition] = '咬';
            }

            //打印赛道当前的情况
            for(int i = 0; i < road.length; i++)
            {
                System.out.print(road[i]);
            }


            Thread.sleep(300);

            System.out.println();
        }

        if(tPosition >= 70)
        {
            System.out.println("乌龟赢了");
        }
        else//hPosition >= 70
        {
            System.out.println("兔子赢了");
        }
    }
}

统计单词次数

一个文件(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

要求统计该文章中各个单词出现的次数,并且按次数出现多少从多到少排序,将结果输出至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)//还有未曾读完的内容
        {
            stringBuilder.append(strContent);
            //继续读取下一行
            strContent = bufferedReader.readLine();
        }
        System.out.println(stringBuilder.toString());

        //用空格分隔,打破成字符串数组
        String[] words = stringBuilder.toString().split(" ");
        System.out.println(words);

        //定义一个map结构,key保存单词,值保存单词出现的次数
        Map<String,Integer> word2Counts = new HashMap<>();

        //将单词从数组结构,转换为map结构
        for(String word : words)
        {
            //考察每个单词,如果单词出现在Map的key中,取出对应的值(也就是该单词已经出现的次数),
            //将其加1,然后放回map
            if(word2Counts.containsKey(word))
            {
                int count = word2Counts.get(word);
                count++;
                word2Counts.put(word,count);
            }
            else//否则,意味着该单词首次出现,那么将该单词放入map中,并且将次数设置为1
            {
                word2Counts.put(word,1);
            }

        }

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


        //将单词信息,从map结构转换到list结构
        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;
    }
}

推荐阅读