Java Lab

Lab 1

新学期,新的语言学习开始了~还是老样子,写代码~

public class TestArgs {
    public static void main (String[] args) {
        System.out.println("Name            = " + args[0] + " " + args[1]);
        System.out.println("BUPT Email Username = " + args[2]);
        System.out.println("Student Number      = " + args[3]);
    }
}

public class WeekDayConverter {
    public static void main(String[] args) {
        int weekDay = Integer.parseInt(args[0]);
        switch (weekDay) {
            case 1:
                System.out.println("The 1st day of week is Mon!");
                break;
            case 2:
                System.out.println("The 2nd day of week is Tue!");
                break;
            case 3:
                System.out.println("The 3rd day of week is Wed!");
                break;
            case 4:
                System.out.println("The 4th day of week is Thu!");
                break;
            case 5:
                System.out.println("The 5th day of week is Fri!");
                break;
            case 6:
                System.out.println("The 6th day of week is Sat!");
                break;
            case 7:
                System.out.println("The 7th day of week is Sun!");
                break;
            default:
                System.out.println("Error!");
        }
    }
}
public class BMICalculator {
    public static void main(String[] args) {
        float weight = Float.parseFloat(args[0]);
        float height = Float.parseFloat(args[1]) / 100;
        float BMI = weight / (height * height);
        System.out.println("Your weight: " + weight + " kg");
        System.out.println("Your height: " + height + " m");
        System.out.printf("Your BMI: %4.2fn", BMI);
        if (BMI < 18.5F) {
            System.out.println("You are in the Underweight range.");
        } else if (BMI < 25F) {
            System.out.println("You are in the Normal range.");
        } else if (BMI < 30F) {
            System.out.println("You are in the Overweight range.");
        } else {
            System.out.println("You are in the Obese range.");
        }
    }
}
public class DoublingNumbers1 {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("The double of " + i + " is " + 2 * i);
            i++;
        } while (i < 11);
    }
}
public class DoublingNumbers2 {
    public static void main(String[] args) {
        for (int i = 1; i < 11; i++) {
            System.out.println("The double of " + i + " is " + 2 * i);
        }
    }
}

Lab 2

第二次的 Java 实验,比第一次有了点意思~不过第一个题。。。这是几岁小孩的游戏啊,竟然是拼代码!当我看到这个题的时候,一口老血,噗!

public class JavaTest {
    public static void main(String[] args) {
        int loopUntil = Integer.parseInt(args[0]);
        System.out.println();
        for (int i = 0; i < loopUntil; i++) {
            System.out.print(i);
            System.out.print(":");
            for (int j = loopUntil; j > 0; j--) {
                if (((i + j) % 3) == 0) {
                    System.out.print("*");
                } else {
                    System.out.print(j);
                }
            }
            System.out.println();
        }
    }
}
public class Pattern1 {
    public static void main(String[] args) {
        int loopUntil = Integer.parseInt(args[0]);
        for (int i = 1; i <= loopUntil; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}
public class Pattern2 {
    public static void main(String[] args) {
        int loopUntil = Integer.parseInt(args[0]);
        for (int i = loopUntil; i > 0; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }
}
public class Patterns {

    public void printPattern1(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }

    public void printPattern2(int n) {
        for (int i = n; i > 0; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int loopUntil = Integer.parseInt(args[0]);

        Patterns Pattern1 = new Patterns();
        Pattern1.printPattern1(loopUntil);

        Patterns Pattern2 = new Patterns();
        Pattern2.printPattern2(loopUntil);
    }
}

第五个题,是关于 Javadoc 的,其实有点不太懂,目前也不知道有没有软件可以辅助编写注释的,只能手打了,这个是题目中给的 java 范例:

public class CountDownExample {

    /**
     * This method counts down from a specified number
     * to zero. It will print its progress to the
     * command line.
     * @param count The number to count from.
     */
    public void countDown(int count) {
        /**
         * Note: If there are no brackets after a for
         * loop, it is only the sentence that
         * immediatly follows that is part of the loop.
         */
        for (int i=count; i > 0; i--)
            System.out.println(i);

        System.out.println("nTime up!");
    }

    /**
     * Main now only creates a new instance of my
     * program and calls the program's method.
     * @param args This program does not use this parameter.
     */
    public static void main (String[] args) {
        CountDownExample q = new CountDownExample();
        q.countDown(5);
    }
}

在创建了 docCD 文件夹之后,运行这样的命令就可以在 docCD 文件夹里看到 Javadoc 文档了:

javadoc –d docCD CountDownExample.java
public class CountUpExample {
    /**
     * This method counts down from a specified number
     * to zero. It will print its progress to the
     * command line.
     * @param count The number to count from.
     */
    public void countUp(int count) {
        /**
         * Note: If there are no brackets after a for
         * loop, it is only the sentence that
         * immediatly follows that is part of the loop.
         */
        for (int i = 1; i <= count; i++) {
            System.out.println(i);
        }
        System.out.println("nAll done!");
    }
    /**
     * Main now only creates a new instance of my
     * program and calls the program's method.
     * @param args This program does not use this parameter.
     */
    public static void main (String[] args) {
        CountUpExample q = new CountUpExample();
        q.countUp(5);
    }
}

Lab 3

第三次的 Java 实验中,用到了 Color 类,对于这个类,我很不熟悉,写这一次的实验代码花了好多时间,但其实到现在第一题的代码写的也不好,在 CatTest 中输出猫的颜色不知道除了枚举还有什么方法~~大家凑合着看吧~

首先是第一题的 Cat.java,Setter 和 Getter 重复写那么多也是挺无聊的。

import java.awt.*;

/**
 * Title        Cat.java
 * Description  This class contains the definition of a cat.
 * Copyright    Copyright (c) 2006 - 2016
 * @author      Laurissa Tokarchuk
 * @version     1.0
 * @author      Paula Fonseca
 * @version     1.1
 * @author      Question
 * @version     1.2
 */
public class Cat {
    // Declaration of instance variables.
    private String  name, furType;
    private boolean tail;
    private Color   colour;
    private int  speed;

    //Initialize all instance variables.
    public Cat(String name, String furType, boolean tail, Color colour, int speed) {
        this.name = name;
        this.furType = furType;
        this.tail = tail;
        this.colour = colour;
        this.speed = speed;
    }

    /** This is the sleep method for the cat. It dictates the number of
     *  minutes the cat sleeps.
     *  @param duration  The number of minutes to sleep.
     */
    public void sleep(int duration) {
        System.out.println("I am sleeping for " + duration + " minutes.");
    }

    /** This method allows the cat to run. The distance (in a straight line)
     *  the cat runs is dependent on how long the cat runs and whether or not
     *  it is running in a zigzag.
     *  @param duration  The number of minutes to run.
     *  @param zigzag   Whether to run in a zigzag pattern.
     *  @return int  Number of metres ran.
     */
    public int run(int duration, boolean zigzag) {
        System.out.println("I am running "
                           + (zigzag? "in a zigzag" : "straight")
                           + " for "
                           + duration
                           + " minutes.");
        int distanceRun = duration * speed; // assuming speed is metres per minute
        if (zigzag) {
        /* When in zigzag, distance is 1/3 of what it would have been if
           the cat was going straight. */
            return distanceRun/3;
        }
        else return distanceRun;
    }

    /** The setter method of name.
     */
    public void setName(String name) {
        this.name = name;
    }

    /** The setter method of speed.
     */
    public void setSpeed(int speed) {
        this.speed = speed;
    }

    /** The getter method of name.
     *  @return name The name of cat.
     */
    public String getName() {
        return name;
    }

    /** The getter method of speed.
     *  @return speed The speed of cat.
     */
    public int getSpeed() {
        return speed;
    }

    /** The getter method of color.
     *  @return colour The color of cat.
     */
    public Color getColor() {
        return colour;
    }
}

然后是 CatTest.java,这里有一个需要注意的地方就是,这里开头也要写 import,不写报错,QMUL 的老师也是挺坑的。Color 的输出搞了几天仍然没有搞很明白,网上许多的写法是写个 Enum,但我有点懒,不想整那个了,随便写写拉倒吧,辣鸡 Cat。

import java.awt.*;

/**
 * Title        CatTest.java
 * Description  This class contains the test class for Cat.
 * Copyright    Copyright (c) 2006 - 2016
 * @author      Laurissa Tokarchuk
 * @version     1.0
 * @author      Paula Fonseca
 * @version     1.1
 * @author      Question
 * @version     1.2
 */
public class CatTest {
    public static void main(String[] args) {
/*
        Cat c = new Cat("Napoleon", "straight", true, Color.gray, 5);
        c.setName("Napoleon");
        c.setSpeed(10); // in metres per minute
        c.sleep(5);
        int m = c.run(10, true);
        System.out.println("I have run " + m + " metres.");
        System.out.println("My name is " + c.getName() + ", and my speed is " + c.getSpeed() + ".");
*/

        //Create two cats with all attributes.
        Cat cat1 = new Cat("Princess", "short", false, Color.WHITE, 10);
        Cat cat2 = new Cat("Whiskers", "long", true, Color.GRAY, 15);

        //Print out the name and color of first cat.
        System.out.println("Hi, I'm " + cat1.getName() + ", and I'm " + cat1.getColor().toString() + ".");
        cat1.run(10, false);

        //Print out the name and color of second cat.
        System.out.println("Hi, I'm " + cat2.getName() + ", and I'm " + cat2.getColor().toString() + ".");
        cat2.run(5, true);
    }
}

第二题就是写个计算矩形面积,没有什么好说的,很快就写出来了。

/**
 * Title        Rectangle.java
 * Description  This class contains the definition and test class for rectangle.
 * Copyright    Copyright (c) 2016
 * @author      Question
 * @version     1.0
 */
public class Rectangle {
    // Declaration of instance variables.
    private float l, w;

    // This is the constuctor of Rectangle. Get the length and width of rectangle.
    public Rectangle(float length, float width) {
        l = length;
        w = width;
    }

    /** Calculate the area of rectangle.
     *  @return l*w The area of rectangle.
     */
    public float calcArea() {
        return l * w;
    }

    public static void main(String[] args) {
        //Create two rectangles.
        Rectangle rec1 = new Rectangle(8, 6);
        Rectangle rec2 = new Rectangle(7, 7);
        Rectangle rec3 = new Rectangle(5, 3);

        //Print out the area of two rectangles.
        System.out.println("The first rectangle's area is " + rec1.calcArea() +".");
        System.out.println("The second rectangle's area is " + rec2.calcArea() +".");
        System.out.println("The third area is " + rec3.calcArea() + ".");
    }
}

最后一题,好像……没什么吐槽的地方……但是这个 Javadoc 注释真是写着让人蛋疼啊……

/**
 * Title        Counter.java
 * Description  This class contains the definition of a counter.
 * Copyright    Copyright (c) 2016
 * @author      Question
 * @version     1.0
 */
public class Counter {
    // Declaration of instance variables.
    private int count, max;

    /** This is constructor with two parameters.
     *  @param count The number you need to count.
     *  @param max The max of count number.
     */
    public Counter(int count, int max) {
        this.count = count;
        this.max = max;
    }

    /** This is constructor without parameter.
     *  And set count 0, set max 10.
     */
    public Counter() {
        count = 0;
        max = 10;
    }

    /** This method increases the count value by 2.
     *  @return count The count.
     */
    public int increase() {
        count += 2;
        if(count > max) {
            reset();
        }
        return count;
    }

    /** This method increases the count value by n.
     *  @param n The value you want increase.
     *  @return count The count.
     */
    public int increase(int n) {
        count += n;
        if(count > max) {
            reset();
        }
        return count;
    }

    /** This method decreases the count value by 1.
     *  @return count The count.
     */
    public int decrease() {
        count -= 1;
        if(count < 0){
            reset();
        }
        return count;
    }

    /** This method decreases the count value by n.
     *  @param n The value you want to decrease.
     *  @return count The count.
     */
    public int decrease(int n) {
        count -= n;
        if(count < 0){
            reset();
        }
        return count;
    }

    /** This method doubles the count value.
     *  @return count The count.
     */
    public int doubler() {
        count *= 2;
        return count;
    }

    /** This method resets the count value to 0.
     *  And print out "Counter Reset!".
     */
    public void reset() {
        count = 0;
        System.out.println("Counter Reset!");
    }

    /** This method defines the String of this class.
     *  @return String The count and max of current.
     */
    public String toString() {
        return "Count: " + count + "Max:   " + max;
    }

    /** This method is a getter of count.
     *  @return int The count.
     */
    public int getCount() {
        return count;
    }

    /** This method is a getter of max.
     *  @return int The max.
     */
    public int getMax() {
        return max;
    }

    /** This method is a setter of count.
     *  Everybody can use this method to change count.
     */
    public void setCount(int n) {
        this.count = n;
    }

    /** This method is a setter of max.
     *  Everybody can use this method to change max.
     */
    public void setMax(int n) {
        this.max = n;
    }
}

然后是 CounterTest.java

/**
 * Title        CounterTest.java
 * Description  This class contains the test class for counter.
 * Copyright    Copyright (c) 2016
 * @author      Question
 * @version     1.0
 */
public class CounterTest {
    public static void main(String[] args) {
        //Create a object of Counter.
        Counter c = new Counter();

        //Show the details of counter.
        System.out.println("The max of counter is "
                           + c.getMax()
                           + ", and counter will increase by 2.");
        c.setMax(20);
        c.setCount(10);
        System.out.println("Now the max of counter is "
                           + c.getMax()
                           + ", and the counter will increase from "
                           + c.getCount()
                           + ".");

        //Reset the count, and show the change of every operations.
        c.reset();
        System.out.println("Increase once, the counter is "
                           + c.increase()
                           + ".");
        System.out.println("Decrease once, the counter is "
                           + c.decrease()
                           + ".");
        System.out.println("Double once, the counter is "
                           + c.doubler()
                           + ".");

        c.reset(); /* Reset the count. */
        while(true) {
            int m = c.increase(1);
            System.out.println(m);
            if (m == 0) {
            /* When n = 0, the counter is over, so need to kill the loop. */
                break;
            }
        }

        c.setCount(20); /* Set the count = 20.*/
        while(true) {
            int m = c.decrease(3);
            System.out.println(m);
            if (m == 0) {
            /* When n = 0, the counter is over, so need to kill the loop. */
                break;
            }
        }
    }
}

Lab 4

隔了好久,直到第三周 Java 课都上完了才想起来要把 Lab4 的代码赶紧写了。第三周的课讲的好快,而且感觉是目前最重要的内容……这实在是有点让人头疼。但是这周讲到最令人激动的 GUI 部分了,大概以后写的实验代码都会是图形操作界面的吧,想想还是挺让人激动的,终于可以写带图形的程序了。其实在去年这个时候学的 C 语言也可以写图形化的程序,但是学校没有教,想想 C 语言执行效率这么高的语言却没有学到图形化,只能写 Java 的图形化程序,还是有点遗憾的。

Lab4 涉及到的知识大部分在第二周的课件中,不熟悉的可以回去多翻翻第二周课件。有些基本的格式还是需要注意的,我写第二个随机数组的时候,运行总是报空指针的错误,来来回回看了半天才发现是数组忘了 new……

第一题里面用到了 Lab3 的 Cat.java,这里我就不放出来了,看看新的 CatTest2.java 就好了:

/**
 * A class that test Cat class.
 *
 * @author      Question
 * @date        Apr 29, 2016
 * @version     1.0
 */
import java.awt.Color;

public class CatTest2 {
    public static void main(String[] args) {
        // Instance array variable.
        Cat[] test = new Cat[6];

        // Create 6 different cats.
        test[0] = new Cat("Napoleon", "straight", true, Color.GRAY, 5);
        test[1] = new Cat("Princess", "short", false, Color.WHITE, 10);
        test[2] = new Cat("Whiskers", "long", true, Color.GRAY, 15);
        test[3] = new Cat("Tom", "long", true, Color.BLUE, 10);
        test[4] = new Cat("Jerry", "straight", true, Color.YELLOW, 10);
        test[5] = new Cat("Bob", "short", false, Color.BLACK, 15);

        // Use a for loop to print all cats' attributes.
        for (int i = 0; i < test.length; i++) {
            System.out.println(test[i]);
        }
    }
}

第二个是随机数组,随机生成指定数量的 0 至 9 范围的整数,并计算和与均值:

/**
 * A class that represents a random array.
 *
 * @author      Ling Ma
 * @date        Jan 19, 2009
 * @version     1.0
 * @author      Paula Fonseca
 * @date        Apr 11, 2016
 * @version     1.1
 * @author      Question
 * @date        Apr 29, 2016
 * @version     1.2
 */
public class RandomArray {
    private int[] array; // instance variable

    /**
     *  Constructor
     *  @param  size  The size of the array.
     */
    public RandomArray(int size) {
        // Check to see if the user has actually sent a postive number to the method.
        if (size <= 0) {
            System.out.println("Please input a postive integer. Example: java RandomArray 5");
            System.exit(-1);
        }

        // Create an array of int.
        array = new int[size];

        // Use a for loop to give all random number.
        for (int i = 0; i < size; i++) {
            array[i] = (int) (Math.random() * 10);
        }
    }

    /**
     *  A method to print the array elements.
     */
    public void printArray() {
        // Use a for loop to print all numbers.
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    /**
     *  A method to calculate the sum of all elements.
     *  @return  The sum.
     */
    public int calcSum() {
        // Calculate the sum of array.
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        return sum;
    }

    /**
     *  A method to calculate the mean (or average) of all elements.
     *  @return  The mean.
     */
    public double calcMean() {
        // Calculate the average of array.
        double mean = calcSum() / array.length;
        return mean;
    }

    /**
     *  A main method to test.
     */
    public static void main(String[] args) {
        // Check to see if the user has actually sent a parameter to the method.
        if (args.length != 1) {
            System.out.println("Usage: java RandomArray <NUM>. Example: java RandomArray 5");
            System.exit(-1);
        }

        // Create an instance of the class.
        RandomArray test = new RandomArray(Integer.parseInt(args[0]));

        // Print the array.
        test.printArray();

        // Calculate the sum of all the values in the array and print it.
        System.out.println("Sum: " + test.calcSum());

        // Calculate the mean of all the values in the array and print it.
        System.out.println("Mean: " + test.calcMean());
    }
}

Lab 5

这周二的 Java 测试,31 个选择题,做的是相当的爽啊~酸爽~

首先是前后左右相邻的两个人的卷子不一样,一个考场分 A1 和 A2 卷,前所未闻啊,估计不同时间考试的话还会有 B1 和 B2 卷,英国老师这想法真是给跪了,这样的防作弊,我还真是头一次见到。

让我跪了的不只是这个形式,还有考试内容,有的题完全就是问你前几次代码实验的内容,如果不是自己写的代码那题还真没法做,有的题干脆就直接问你 Lab4 实验中第二题的函数都叫什么名称,听说过,没见过,这和以前网上的新闻说某高校期末考试题是一个照片选择题,要求选出哪个是老师差不多,这头一次见到这样考的啊……

幸好,我在五一之前写完了第四次的实验代码,这才不至于栽了跟头。也有同学很幸运,自己没有写代码,看了我的代码之后竟然记住了 Lab4 代码里函数的名称,那个选择题他写对了~

好了,不说了,各位同学以后要好好写代码哦~下面是这次的实验代码内容。

第一题里,又用到了第三次实验的 Cat.java,我还是不放出来了,有需要的同学自己去看我的上一篇博客。

这里我建议可以先看看第二题的 StudentList.java,看了之后会对第一题有一点帮助。

/**
 * A class that test Cat class.
 *
 * @author      Question
 * @date        May 7, 2016
 * @version     1.0
 */
import java.awt.Color;
import java.util.ArrayList;

public class CatTest3 {
    public static void main(String[] args) {
        // Create an ArrayList which will contains many objects.
        ArrayList<Cat> list = new ArrayList<Cat>(5);

        // Create 5 different cats and add them to ArrayList.
        list.add(new Cat("Napoleon", "straight", true, Color.GRAY, 5));
        list.add(new Cat("Princess", "short", false, Color.WHITE, 10));
        list.add(new Cat("Whiskers", "long", true, Color.GRAY, 15));
        list.add(new Cat("Tom", "long", true, Color.BLUE, 10));
        list.add(new Cat("Jerry", "straight", true, Color.YELLOW, 10));

        // Print out the object of index 4.
        System.out.println(list.get(4));

        // Print out the size of ArrayList.
        System.out.println("The size of ArrayList is " + list.size() + ".");

        // Remove the object of index 3.
        list.remove(3);

        // Use a for loop to print out all cats' details.
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

当写完 CatTest3,并且终于没有错误的时候,第二题写起来就非常的快了。

首先是实验给的 Student.java,不需要有任何改动,只用下载下来就可以了,这里我贴出来方便看:

/**
 *  A class that represents a student.
 *  @author  Ling Ma
 *  @created 2009
 *  @version 1.0
 *  @author  Paula Fonseca
 *  @version 1.1
 */
public class Student {
    private String firstName;
    private String lastName;
    private String email;
    private int year; // Year of registration on the course.

    /**
     *  Constructor
     *  @param  first name, last name, email and year of registration
     */
    public Student(String firstName, String lastName, String email, int year) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.year = year;
    }

    /**
     *  Get the first name.
     *  @return  The student's first name.
     */
    public String getFirstName() { return firstName; }

    /**
     *  Get the last name.
     *  @return  The student's last name.
     */
    public String getLastName() { return lastName; }

    /**
     *  A toString() method to give a String representation of a Student.
     *  @return  The String representation of a Student.
     */
    public String toString() {
        String fullName = firstName + " " + lastName;
        return "Name: " + fullName + " Email: " + email + " Year: " + year;
    }
}

然后是很快写好的 StudentList.java

import java.util.ArrayList;

/**
 *  A class that holds a list of students.
 *
 *  @author Question
 *  @date   May 7, 2016
 */
public class StudentList {
    private ArrayList<Student> list; // instance variable

    /**
     *  Constructor
     */
    public StudentList() { list = new ArrayList<Student>(); }

    /**
     *  A method to print off all ArrayList elements.
     */
    public void printList() {
        System.out.println("--Begin--");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        System.out.println("--End--");
    }

    /**
     *  A method to add a student to the list.
     *  @param  The student.
     */
    public void addToList(Student stu) {
        list.add(stu);
        System.out.println(stu.getFirstName()
                           + " "
                           + stu.getLastName()
                           + " has been added to the student list");
    }

    /**
     *  A method to remove a student from the list.
     *  @param  The student.
     */
    public void removeFromList(Student stu) {
        boolean isRemove = list.remove(stu);
        if(isRemove) {
            System.out.println(stu.getFirstName()
                               + " "
                               + stu.getLastName()
                               + " has been removed from the list");
        } else {
            System.out.println("Woops! Something wrong! Failed to delete this student.");
        }
    }

    /**
     *  A main() method to test.
     */
    public static void main(String[] args) {
        // Create an instance of the class.
        StudentList studentList = new StudentList();

        // Create 3 student objects.
        Student stu1 = new Student("John", "Smith", "js@qmul.ac.uk", 2011);
        Student stu2 = new Student("Mary", "Davis", "md@qmul.ac.uk", 2012);
        Student stu3 = new Student("Sherlock", "Holmes", "xxx@qmul.ac.uk", 2014);

        // Add the 3 students to the list.
        studentList.addToList(stu1);
        studentList.addToList(stu2);
        studentList.addToList(stu3);

        // Print the list.
        studentList.printList();

        // Remove the student "Mary Davis"
        studentList.removeFromList(stu2);

        // Print the list again
        studentList.printList();
    }
}

Lab 6

Java 的大作业在今天(2016-05-17)公布了,要求半个月时间写好,目测又是一波波哀嚎接连不断,我稍微看了两眼,是要求编写一个图形化的点菜系统,老师给的要求足足有 4 页那么多……丧心病狂的英方课……说到丧心病狂,还是应该数企管产开最变态,算了不扯了,都是伤心事……

这次的 Lab6 和上次的 Lab5 感觉在难度和水平上都比以前提升了一大截,有点让人招架不住,Lab6 建议还是好好写,自己写,毕竟又是一次要验收的实验。

第一题写的很慢,我的渣英语,题都看不懂,实在是心累,找同学帮忙翻译才明白啥意思。首先是老师提供的 MonsterMash.java,添加了几个怪到 List 里,然后所有的怪都出来打一轮,直到某一轮打完,伤害累积超过 100 就结束,不用修改:

import java.util.*;

/**
 *  Title      : MonsterMash.java
 *  Description: This class is the test class for Monsters.
 *  @author  Laurissa Tokarchuk
 *  @version 1.0
 *  @author  Paula Fonseca
 *  @version 1.1
 */
public class MonsterMash {
    public static void main(String[] args) {
        ArrayList<Monster> monsters = new ArrayList<Monster>();

        monsters.add(new Monster("Tom"));
        monsters.add(new Monster("George"));

        monsters.add(new Dragon("Smaug"));
        monsters.add(new Dragon("Jabosh"));

        monsters.add(new Troll("Salomon"));
        monsters.add(new Troll("Bender"));

        int damageDone = 0;
        while (damageDone < 100) {
            for (Monster m : monsters) {
                m.move((int)(Math.random()*4) + 1);
                damageDone += m.attack();
            }
        }
    }
}

2016-05-18 更新:这里面最后一段代码,for 函数与我们之前见到的都不一样,今天有同学问我我才注意到,这里的 for 函数括号中间有两部分,用冒号(colon)隔开,其实是 foreach 函数,用来遍历,在这里的作用就是将 monsters 里面所有的对象都调出来,并建立引用(reference),将所有的对象都 move 一下,attack 一下。

定义一个 Monster 类,包括了怪的通用的方法(method),attack 和 move,如果你在这里也把 name 设置成 private,就需要像我一样多写一个 setter 和 getter 函数:

/**
 *  A class that defines monster.
 *
 *  @author Question
 *  @date   May 14, 2016
 */
public class Monster {
    // Instance variables.
    private String name;

    // Constructor.
    public Monster(String newName) {
        name = newName;
    }

    /**
     *  A setter method.
     *  @param newName The new name you want to set.
     */
    public void setName(String newName) {
        name = newName;
    }

    /**
     *  A getter method.
     *  @return name The name of monster.
     */
    public String getName() {
        return name;
    }

    /**
     *  A method to add a student to the list.
     *  @return attackValue The value of monster's attack.
     */
    public int attack() {
        int attackValue = (int) (Math.random() * 5 + 1); // Random attack between 1 and 5.
        System.out.println(name + ", of type "
                           + this.getClass() + ", attacks generically: "
                           + attackValue + " points damage caused.");
        return attackValue;
    }

    /**
     *  A method to show which direction the monster move.
     *  @param direction The direction of monster.
     */
    public void move(int direction) {
        switch(direction) {
            case 1:
                System.out.println(this.name + " is moving 1 step NORTH.");
                break;
            case 2:
                System.out.println(this.name + " is moving 1 step EAST.");
                break;
            case 3:
                System.out.println(this.name + " is moving 1 step SOUTH.");
                break;
            default:
                System.out.println(this.name + " is moving 1 step WEST.");
                break;
        }
    }
}

接下来写龙这种怪(感觉怪怪的),题目写明:30% 的时间龙是用龙息(吐火)来攻击的,剩下的时间是普通攻击,在这里时间上的分割其实可以用随机数来代替实现,随机生成 1 到 10 的整数,小于等于 3 时使用龙息:

/**
 *  A class that defines dragon.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public class Dragon extends Monster {
    // Constructor.
    public Dragon(String newName) {
        super(newName);
    }

    /**
     *  Attack method of Dragon.
     *  @return attackValue The value of dragon's attack.
     */
    public int attack() {
        int timeSelect = (int) (Math.random() * 10 + 1); // Random integer number to decide how to attack.
        if(timeSelect <= 3) { // 30% of the time.
            int attackValue = (int) (Math.random() * 50 + 1); // Random attack between 1 and 50.
            System.out.println(this.getName() + ", of type "
                               + this.getClass() + ", attacks by breathing fire: "
                               + attackValue + " points damage caused.");
            return attackValue;
        } else {
            return super.attack();
        }
    }
}

然后是 Troll 这货,这是个啥我也不知道,英语渣:

/**
 *  A class that defines troll.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public class Troll extends Monster {
    // Constructor.
    public Troll(String newName) {
        super(newName);
        if(newName.equals("Saul") || newName.equals("Salomon")) { // If the name is Saul,
            System.out.println("Error!"); // print Error and
            setName("Detritus"); // set new name.
        }
    }
}

都写好之后,运行 MonsterMash 就出来一大片各种怪的攻击记录。

第二题在第一题的基础上有了更多的要求,将 Monster 变成抽象类,强制所有怪都要有特殊攻击方式,并定义了个特殊攻击的概率。Monster:

/**
 *  A class that defines monster.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public abstract class Monster implements SpecialAttack {
    // Instance variables.
    private String name;
    private double spAttackProbability = 0.2;

    /**
     *  A constructor.
     *  @param newName The new name you want to set.
     */
    public Monster(String newName) {
        name = newName;
    }

    /**
     *  A another constructor.
     *  @param newName The new name you want to set.
     *  @param spAttackProbability The probability of special attack you want to set.
     */
    public Monster(String newName, double spAttackProbability) {
        name = newName;
        this.spAttackProbability = spAttackProbability;
    }

    /**
     *  A setter method.
     *  @param newName The new name you want to set.
     */
    public void setName(String newName) {
        name = newName;
    }

    /**
     *  A getter method.
     *  @return name The name of monster.
     */
    public String getName() {
        return name;
    }

    /**
     *  A method to add a student to the list.
     *  @return attackValue The value of monster's attack.
     */
    public final int attack() {
        if(Math.random() < spAttackProbability) {
            return this.specialAttack();
        } else {
            int attackValue = (int) (Math.random() * 5 + 1); // Random attack between 1 and 5.
            System.out.println(name + ", of type "
                               + this.getClass() + ", attacks generically: "
                               + attackValue + " points damage caused.");
            return attackValue;
        }
    }

    /**
     *  A method to show which direction the monster move.
     *  @param direction The direction of monster.
     */
    public void move(int direction) {
        switch(direction) {
            case 1:
                System.out.println(this.name + " is moving 1 step NORTH.");
                break;
            case 2:
                System.out.println(this.name + " is moving 1 step EAST.");
                break;
            case 3:
                System.out.println(this.name + " is moving 1 step SOUTH.");
                break;
            default:
                System.out.println(this.name + " is moving 1 step WEST.");
                break;
        }
    }
}

因为题目要求所有的怪强制定义特殊攻击,所以就想到了就接口来实现:

/**
 *  An interface that force classes to provide specialAttack method.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public interface SpecialAttack {
    public int specialAttack();
}

然后在 Dragon.javaTroll.java 里加上 specialAttack 函数就好了:

/**
 *  A class that defines dragon.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public class Dragon extends Monster {
    // Instance variable.
    private static double spAttackProbability = 0.3;

    // Constructors.
    public Dragon(String newName) {
        super(newName, spAttackProbability);
    }

    public Dragon(String newName, double newProbability) {
        super(newName, newProbability);
    }

    /**
     *  Special attack method of Dragon.
     *  @return attackValue The value of dragon's attack.
     */
    public int specialAttack() {
        int attackValue = (int) (Math.random() * 50 + 1); // Random attack between 1 and 50.
        System.out.println(this.getName() + ", of type "
                           + this.getClass() + ", attacks by breathing fire: "
                           + attackValue + " points damage caused.");
        return attackValue;
    }
}
/**
 *  A class that defines troll.
 *
 *  @author Question
 *  @date   May 17, 2016
 */
public class Troll extends Monster {
    // Constructors.
    public Troll(String newName) {
        super(newName);
        if(newName.equals("Saul")) { // If the name is Saul,
            System.out.println("Error!"); // print Error and
            setName("Detritus"); // set new name.
        }
        if(newName.equals("Salomon")) { // If the name is Saul,
            System.out.println("Error!"); // print Error and
            setName("Detritus"); // set new name.
        }
    }

    public Troll(String newName, double newProbability) {
        super(newName, newProbability);
        if(newName.equals("Saul")) { // If the name is Saul,
            System.out.println("Error!"); // print Error and
            setName("Detritus"); // set new name.
        }
        if(newName.equals("Salomon")) { // If the name is Saul,
            System.out.println("Error!"); // print Error and
            setName("Detritus"); // set new name.
        }
    }

    /**
     *  Special attack method of Troll.
     *  @return attackValue The value of dragon's attack.
     */
    public int specialAttack() {
        int attackValue = (int) (Math.random() * 15 + 1); // Random attack between 1 and 15.
        System.out.println(this.getName() + ", of type "
                           + this.getClass() + ", attacks by hiting with a club: "
                           + attackValue + " points damage caused.");
        return attackValue;
    }
}

最后,原先的 MonsterMash.java 已经不能编译了,因为 Monster 已经变成了抽象类,不能实例化,需要修改一下:

import java.util.*;

/**
 *  Title      : MonsterMash.java
 *  Description: This class is the test class for Monsters.
 *  @author  Laurissa Tokarchuk
 *  @version 1.0
 *  @author  Paula Fonseca
 *  @version 1.1
 *  @author  Question
 *  @version 1.2
 */
public class MonsterMash {
    public static void main(String[] args) {
        ArrayList<Monster> monsters = new ArrayList<Monster>();

        // The Monster class have been modified to an abstract class,
        // so java cannot create monster object.
        /*
        monsters.add(new Monster("Tom"));
        monsters.add(new Monster("George"));
        */

        monsters.add(new Dragon("Smaug"));
        monsters.add(new Dragon("Jabosh"));

        monsters.add(new Troll("Salomon"));
        monsters.add(new Troll("Bender"));

        int damageDone = 0;
        while (damageDone < 100) {
            for (Monster m : monsters) {
                m.move((int)(Math.random()*4) + 1);
                damageDone += m.attack();
            }
        }
    }
}

Lab 7

这次的 Lab7 是在大作业发布之后的实验,所以这次的更新来的有点慢,有同学都开始催我发 Lab7 了。不是我不想发,而是大作业当头我只好先顾着大作业了,反正往后的几次试验都不验收了,所以先放下了实验,专心写大作业。

Java 的大作业,可以说,非常成功的检验了当代大学生“自学成才”的能力 -_-#,可以这么说:我的大作业有几乎一半的知识点都是在网上自己查资料写出来的。老师教的,课件写的,要么是没有相关知识点,要么就是不够好用。

这次大作业和 C 语言大作业一样,都是会在提交日期之后再放出来,没有办法,这东西是要计算成绩的,我也不敢拿我的成绩开玩笑。

其实先写写 Lab7 可能会对大作业比较有帮助,但毕竟已经是现在这个时间了(2016-06-05),说这些意义也不大了~

第一题和第二题的要求我一起看了,第二题的要求就是比第一题多了一个可以自己定义按钮数量的功能,所以我在写第一题的时候就按照第二题的思路来写了,写好第一题之后第二题几乎就是小小改动一下就可以用了。

/**
 * Title        CatchButtonGameV1.java
 * Description  This class contains a game which never will success.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 5th, 2016
 * @version     1.0
 */

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

public class CatchButtonGameV1 extends JFrame {
    private static int number;
    private int size = (int) ((float) (Toolkit.getDefaultToolkit().getScreenSize().width) / 3); // Set the size of GUI.
    private JButton[] gameButton = new JButton[number * number];

    public static void main(String[] args) {
        number = 3;
        CatchButtonGameV1 game = new CatchButtonGameV1();
        game.start();
    }

    // Constructor.
    public CatchButtonGameV1() {
        super("Catch me if you can!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when click the exit button.
        getContentPane().setBackground(new Color(90, 154, 212)); // Set the background color of window.
        setSize(size, size); // Set the size of window.
        setResizable(false); // Forbid to resize the window.
        setLocationRelativeTo(null); // Set the window in the centre of screen.

        initialize();
    }

    /**
     *  This method will create a GridLayout panel and add buttons to it.
     */
    private void initialize() {
        int hap = (int) ((float) (size) / 100);
        JPanel gamePanel = new JPanel(new GridLayout(number, number, hap, hap));
        gamePanel.setOpaque(false);
        for (int i = 0; i < number * number; i++) {
            gameButton[i] = new JButton();
            gamePanel.add(gameButton[i]);
        }
        this.getContentPane().add(gamePanel);

        MouseListener moveOn = new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                int Wooha = 0;
                for (int i = 0; i < number * number; i++) {
                    if (e.getSource().equals(gameButton[i])) {
                        Wooha = i;
                        gameButton[i].setText("");
                        gameButton[i].removeMouseListener(this);
                        break;
                    }
                }

                int i;
                do {
                    i = (int) (Math.random() * number * number);
                } while (i == Wooha);
                gameButton[i].addMouseListener(this);
                gameButton[i].setText("Click me");
            }
        };

        int i = (int) (Math.random() * number * number);
        gameButton[i].addMouseListener(moveOn);
        gameButton[i].setText("Click me");
    }

    private void start() {
        this.setVisible(true);
    }
}
/**
 * Title        CatchButtonGameV2.java
 * Description  This class contains a game which never will success.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 5th, 2016
 * @version     1.0
 */

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

public class CatchButtonGameV2 extends JFrame {
    private static int number;
    private int size = (int) ((float) (Toolkit.getDefaultToolkit().getScreenSize().width) / 3); // Set the size of GUI.
    private JButton[] gameButton = new JButton[number * number];

    public static void main(String[] args) {
        if (args.length < 1 || Double.parseDouble(args[0]) < 9) {
            System.out.println("Usage:\n Java CatchButtonGameV2 16(or 9, 25)");
            System.exit(0);
        }
        number = (int) Math.sqrt(Double.parseDouble(args[0]));
        CatchButtonGameV2 game = new CatchButtonGameV2();
        game.start();
    }

    // Constructor.
    public CatchButtonGameV2() {
        super("Catch me if you can!");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when click the exit button.
        getContentPane().setBackground(new Color(90, 154, 212)); // Set the background color of window.
        setSize(size, size); // Set the size of window.
        setResizable(false); // Forbid to resize the window.
        setLocationRelativeTo(null); // Set the window in the centre of screen.

        initialize();
    }

    /**
     *  This method will create a GridLayout panel and add buttons to it.
     */
    private void initialize() {
        int hap = (int) ((float) (size) / 100);
        JPanel gamePanel = new JPanel(new GridLayout(number, number, hap, hap));
        gamePanel.setOpaque(false);
        for (int i = 0; i < number * number; i++) {
            gameButton[i] = new JButton();
            gamePanel.add(gameButton[i]);
        }
        this.getContentPane().add(gamePanel);

        MouseListener moveOn = new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                int Wooha = 0;
                for (int i = 0; i < number * number; i++) {
                    if (e.getSource().equals(gameButton[i])) {
                        Wooha = i;
                        gameButton[i].setText("");
                        gameButton[i].removeMouseListener(this);
                        break;
                    }
                }

                int i;
                do {
                    i = (int) (Math.random() * number * number);
                } while (i == Wooha);
                gameButton[i].addMouseListener(this);
                gameButton[i].setText("Click me");
            }
        };

        int i = (int) (Math.random() * number * number);
        gameButton[i].addMouseListener(moveOn);
        gameButton[i].setText("Click me");
    }

    private void start() {
        this.setVisible(true);
    }
}

Lab 8

马上就要考 MCQ2 了,我也不瞎 BB 了,各位有需要的赶紧看啊~

首先看懂题啥意思哈,看不懂题的话你也看不懂我在写啥……这题意思大概是说输入 7 位二进制数,even parity 的时候 0 和 1 的个数都是偶数个,odd parity 的时候 0 和 1 的个数都是奇数个。

/**
 * Title        ParityBitAdder.java
 * Description  This class defines a parity bit adder.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class ParityBitAdder {
    private char[] number;
    private static int oddEven;
    private String result;

    public static void main(String[] args) {
        ParityBitAdder myAdder = new ParityBitAdder(args);
        System.out.println("Adding " + (oddEven > 0 ? "odd" : "even")
                           + " parity to '" + args[0] + "' results in the binary pattern '"
                           + myAdder.getResult() + "'.");
    }

    /**
     *  This constructor just tell the right usage and exit.
     */
    public ParityBitAdder() {
        System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
        System.exit(0);
    }

    /**
     *  This constructor check if user have input right parameters.
     */
    public ParityBitAdder(String[] args) {
        if (args.length != 2 || args[0].length() != 7 || args[1].length() != 1) {
            System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
            System.exit(0);
        }
        number = args[0].toCharArray();
        for (int i = 0; i < number.length; i++) {
            if (!Character.isDigit(number[i]) || Integer.parseInt("" + number[i]) > 1 || Integer.parseInt("" + number[i]) < 0) {
                System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
                System.exit(0);
            }
        }
        if (!Character.isDigit(args[1].charAt(0)) || Integer.parseInt(args[1]) > 1 || Integer.parseInt(args[1]) < 0) {
            System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
            System.exit(0);
        }
        oddEven = Integer.parseInt(args[1]);
    }

    /**
     *  This method call calculateParity method and return result.
     *  @return result The calculation result.
     */
    public String getResult() {
        calculateParity();
        return result;
    }

    /**
     *  This method calculate the parity and add into a string.
     */
    private void calculateParity() {
        int one = 0;
        for (int i = 0; i < number.length; i++) {
            if (Integer.parseInt("" + number[i]) == 1) {
                one++;
            }
        }
        if ((one % 2) == oddEven) {
            result = "0" + (new String(number));
        } else {
            result = "1" + (new String(number));
        }
    }
}
/**
 * Title        StringConverter.java
 * Description  This class defines a string converter.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class StringConverter {
    private String input;
    private String result;

    public static void main(String[] args) {
        StringConverter myConverter = new StringConverter(args);
        System.out.println("Output: " + myConverter.getResult());
    }

    /**
     *  This constructor just tell the right usage and exit.
     */
    public StringConverter() {
        System.out.println("Usage:\njava StringConverter \"My car Goes verY FAST!\"");
        System.exit(0);
    }

    /**
     *  This constructor check if user have input right parameters.
     */
    public StringConverter(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage:\njava StringConverter \"My car Goes verY FAST!\"");
            System.exit(0);
        }
        input = args[0];
    }

    /**
     *  This method call convertString method and return result.
     *  @return result The convertation result.
     */
    public String getResult() {
        convertString();
        return result;
    }

    /**
     *  This method convert the input by some rules.
     */
    private void convertString() {
        String middle = input.toUpperCase();
        middle = middle.replace("A", "a");
        middle = middle.replace("E", "e");
        middle = middle.replace("I", "i");
        middle = middle.replace("O", "o");
        middle = middle.replace("U", "u");
        middle = middle.replace("Y", "y");

        char[] middleChar = middle.toCharArray();
        for (int i = 0; i < middleChar.length; i++) {
            if (!Character.isLetter(middleChar[i])) {
                middleChar[i] = "*".charAt(0);
            }
        }

        result = new String(middleChar);
    }
}

Lab 9

Lab9 里面有两个题都是和 Lab8 相关的,看 Lab9 的话要先把 Lab8 看了。

第一个题是装了个逼,把 Lab8 的代码加个抛出异常~ParityBitAdder 升级到了 v2~

/**
 * Title        ParityBitAdder_v2.java
 * Description  This class defines a parity bit adder.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class ParityBitAdder_v2 {
    private char[] number;
    private static int oddEven;
    private String result;

    public static void main(String[] args) {
        try {
            ParityBitAdder_v2 myAdder = new ParityBitAdder_v2(args);
            System.out.println("Adding " + (oddEven > 0 ? "odd" : "even")
                               + " parity to '" + args[0] + "' results in the binary pattern '"
                               + myAdder.getResult() + "'.");
        } catch (NonBinaryValue e) {
            System.out.println("Error: The first input to this program must be a 7-bit binary number. Please try again!");
            System.exit(0);
        } catch (IllegalParityValue e) {
            System.out.println("Error: The program's parity bit input (the second argument) must be either 0 or 1. Please try again!");
            System.exit(0);
        }
    }

    /**
     *  This constructor just tell the right usage and exit.
     */
    public ParityBitAdder_v2() {
        System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
        System.exit(0);
    }

    /**
     *  This constructor check if user have input right parameters.
     */
    public ParityBitAdder_v2(String[] args) throws NonBinaryValue, IllegalParityValue {
        if (args.length != 2) {
            System.out.println("Usage:\njava ParityBitAdder 1010011 0\nOr:\njava ParityBitAdder 1010011 1");
            System.exit(0);
        }
        if (args[0].length() != 7) {
            throw new NonBinaryValue();
        }
        if (args[1].length() != 1) {
            throw new IllegalParityValue();
        }
        number = args[0].toCharArray();
        for (int i = 0; i < number.length; i++) {
            if (!Character.isDigit(number[i]) || Integer.parseInt("" + number[i]) > 1 || Integer.parseInt("" + number[i]) < 0) {
                throw new NonBinaryValue();
            }
        }
        if (!Character.isDigit(args[1].charAt(0)) || Integer.parseInt(args[1]) > 1 || Integer.parseInt(args[1]) < 0) {
            throw new IllegalParityValue();
        }
        oddEven = Integer.parseInt(args[1]);
    }

    /**
     *  This method call calculateParity method and return result.
     *  @return result The calculation result.
     */
    public String getResult() {
        calculateParity();
        return result;
    }

    /**
     *  This method calculate the parity and add into a string.
     */
    private void calculateParity() {
        int one = 0;
        for (int i = 0; i < number.length; i++) {
            if (Integer.parseInt("" + number[i]) == 1) {
                one++;
            }
        }
        if ((one % 2) == oddEven) {
            result = "0" + (new String(number));
        } else {
            result = "1" + (new String(number));
        }
    }
}

需要抛出的俩异常要自己写出来:

/**
 * Title        NonBinaryValue.java
 * Description  This class defines a custom exception.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class NonBinaryValue extends RuntimeException {
    public NonBinaryValue() {}
    public NonBinaryValue(String message) {
        super(message);
    }
}
/**
 * Title        IllegalParityValue.java
 * Description  This class defines a custom exception.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class IllegalParityValue extends RuntimeException {
    public IllegalParityValue() {}
    public IllegalParityValue(String message) {
        super(message);
    }
}

第二题小改一下,不再是带着参数运行程序了,而是运行中要求用户在控制台输入,就是加个 System.in,最多也就是再来个友好的提示:

/**
 * Title        ParityBitAdder_v3.java
 * Description  This class defines a parity bit adder.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

import java.util.Scanner;

public class ParityBitAdder_v3 {
    private char[] number;
    private static int oddEven;
    private String result;

    public static void main(String[] waste) {
        System.out.println("#########################################");
        System.out.println("#                 Hello                 #");
        System.out.println("#      Welcome use ParityBitAdder!      #");
        System.out.println("#########################################");
        System.out.println("Please input 7-bit binary number:");
        Scanner binaryScanner = new Scanner(System.in);
        String binaryString = binaryScanner.nextLine();
        System.out.println("Please input the type of parity:(0 = even, 1 = odd)");
        Scanner typeScanner = new Scanner(System.in);
        String typeString = typeScanner.nextLine();
        String[] args = {binaryString, typeString};
        try {
            ParityBitAdder_v3 myAdder = new ParityBitAdder_v3(args);
            System.out.println("Adding " + (oddEven > 0 ? "odd" : "even")
                               + " parity to '" + args[0] + "' results in the binary pattern '"
                               + myAdder.getResult() + "'.");
        } catch (NonBinaryValue e) {
            System.out.println("Error: The first input to this program must be a 7-bit binary number. Please try again!");
            System.exit(0);
        } catch (IllegalParityValue e) {
            System.out.println("Error: The program's parity bit input (the second argument) must be either 0 or 1. Please try again!");
            System.exit(0);
        }
    }

    /**
     *  This constructor check if user have input right parameters.
     */
    public ParityBitAdder_v3(String[] args) throws NonBinaryValue, IllegalParityValue {
        if (args[0].length() != 7) {
            throw new NonBinaryValue();
        }
        if (args[1].length() != 1) {
            throw new IllegalParityValue();
        }
        number = args[0].toCharArray();
        for (int i = 0; i < number.length; i++) {
            if (!Character.isDigit(number[i]) || Integer.parseInt("" + number[i]) > 1 || Integer.parseInt("" + number[i]) < 0) {
                throw new NonBinaryValue();
            }
        }
        if (!Character.isDigit(args[1].charAt(0)) || Integer.parseInt(args[1]) > 1 || Integer.parseInt(args[1]) < 0) {
            throw new IllegalParityValue();
        }
        oddEven = Integer.parseInt(args[1]);
    }

    /**
     *  This method call calculateParity method and return result.
     *  @return result The calculation result.
     */
    public String getResult() {
        calculateParity();
        return result;
    }

    /**
     *  This method calculate the parity and add into a string.
     */
    private void calculateParity() {
        int one = 0;
        for (int i = 0; i < number.length; i++) {
            if (Integer.parseInt("" + number[i]) == 1) {
                one++;
            }
        }
        if ((one % 2) == oddEven) {
            result = "0" + (new String(number));
        } else {
            result = "1" + (new String(number));
        }
    }
}

和上一题一样,也用到那俩异常了,直接复制粘贴过来用就行了。

第三题瞎 BB 一堆,又是扯遗传算法又是扯染色体什么玩意儿的,都不用看,直接看小标号的要求就可以了。

/**
 * Title        Chromosome.java
 * Description  This class defines a chromosome.
 * Copyright    (c) 2016 Copyright Holder All Rights Reserved.
 * @author      Question
 * @date        June 13th, 2016
 * @version     1.0
 */

public class Chromosome {
    int[] chromosomeArray;

    /**
     *  Main method creates two Chromosome objects.
     */
    public static void main(String[] args) {
        int[] first = {1, 0, 1, 1, 1, 0, 1};
        int[] second = {3, 5, 2, 2};

        try {
            Chromosome firstChromosome = new Chromosome(first);
            System.out.println(firstChromosome.toString());
            Chromosome secondChromosome = new Chromosome(second);
            System.out.println(secondChromosome.toString());
        } catch (NonBinaryValue e) {
            System.out.println("Error: The input must be a binary number.");
            System.out.println("Wrong chromosome will be reset to default chromosome.");
            e.printStackTrace();
            System.exit(0);
        }
    }

    /**
     *  This constructor check if input is right.
     */
    public Chromosome(int[] args) throws NonBinaryValue {
        chromosomeArray = args;
        for (int i = 0; i < args.length; i++) {
            if (args[i] > 1 || args[i] < 0) {
                for (int j = 0; j < chromosomeArray.length; j++) {
                    chromosomeArray[j] = 1;
                }
                throw new NonBinaryValue();
            }
        }
    }

    /**
     *  This method will calculate the number of "1" and return.
     *  @return one The number of "1".
     */
    public int getFitness() {
        int one = 0;
        for (int i = 0; i < chromosomeArray.length; i++) {
            if (chromosomeArray[i] == 1) {
                one++;
            }
        }
        return one;
    }

    /**
     *  This method transfer chromosome to a string and return.
     *  @return myStringBuffer.toString() The string which contains all numbers of chromosome.
     */
    public String toString() {
        StringBuffer myStringBuffer = new StringBuffer("[");
        for (int i = 0; i < chromosomeArray.length - 1; i++) {
            myStringBuffer.append(chromosomeArray[i]);
            myStringBuffer.append(" ");
        }
        myStringBuffer.append(chromosomeArray[chromosomeArray.length - 1]);
        myStringBuffer.append("]");
        return myStringBuffer.toString();
    }
}

最后扯一句,有时间最好自己看看题,只看我的代码恐怕会在一定程度上影响你们的想法,不是太好~

祝各位,Java 都高分考过!

Java Lab》有4个想法

  1. Panadax

    一看就是国院学长啊啊啊啊啊啊~正在愁LAB7 GUI这块学的乱七八糟的 在GOOGLE上一搜还真搜到了 感谢感谢~

    回复
  2. 傻狍子

    cat1.getColor().toString()开始还以为问少搞出了啥厉害的东西,然后发现和cat1.getColor()一样一样的耶

    回复
    1. Neo 文章作者

      因为在Color的类里,它的toString()函数是定义好了的,所以这里写cat1.getColor()其实就是调用cat1.getColor().toString()

      回复

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注