Wednesday, 26 October 2016

Chapter 11 Exercise 1, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

11.1 (The Triangle class) Design a class named Triangle that extends
GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default
values 1.0 to denote three sides of the triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and
side3.
■ The accessor methods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this triangle.
■ A method named toString() that returns a string description for the triangle.
For the formula to compute the area of a triangle, see Programming Exercise 2.19.
The toString() method is implemented as follows:
return "Triangle: side1 = " + side1 + " side2 = " + side2 +
" side3 = " + side3;
Draw the UML diagrams for the classes Triangle and GeometricObject and
implement the classes. Write a test program that prompts the user to enter three
sides of the triangle, a color, and a Boolean value to indicate whether the triangle
is filled. The program should create a Triangle object with these sides and set
the color and filled properties using the input. The program should display
the area, perimeter, color, and true or false to indicate whether it is filled or not.
Sections 11.5–11.14

public class Triangle extends GeometricObject {

    private double side1;
    private double side2;
    private double side3;


    public Triangle(double side1, double side2, double side3) throws IllegalTriangleException {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
        isValidTriangle();
    }

    public Triangle() {
        this.side1 = 1;
        this.side2 = 1;
        this.side3 = 1;
    }

    @Override
    public double getArea() {

        double s = (side1 + side2 + side3) / 2.0;
        return Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);
    }

    @Override
    public double getPerimeter() {
        return side1 + side2 + side3;
    }

    @Override
    public String toString() {
        return "Triangle{" +
                "side1=" + side1 +
                ", side2=" + side2 +
                ", side3=" + side3 +
                '}';
    }

    public static boolean isTriangle(double side1, double side2, double side3) {

        return  ((side1 + side2 > side3) &&
                (side1 + side3 > side2) &&
                (side3 + side2 > side1));

    }

    public double getSide1() {
        return side1;
    }

    public void setSide1(double side1) throws IllegalTriangleException {
        this.side1 = side1;
        isValidTriangle();
    }

    public double getSide2() {
        return side2;
    }

    public void setSide2(double side2) throws IllegalTriangleException{
        this.side2 = side2;
        isValidTriangle();
    }

    public double getSide3() {
        return side3;
    }

    public void setSide3(double side3) throws IllegalTriangleException {
        this.side3 = side3;
        isValidTriangle();
    }

    private void isValidTriangle() throws IllegalTriangleException{
        if (!isTriangle(side1, side2, side3)) {
            throw new IllegalTriangleException(side1, side2, side3);
        }
    }

    public class IllegalTriangleException extends IllegalArgumentException {

        private double s1;
        private double s2;
        private double s3;

         public IllegalTriangleException(double s1, double s2, double s3) {
            super("Not a real triangle:" + " side1 = " + s1 + " side2 = " + s2 + " side3 = " + s3);
            this.s1 = s1;
            this.s2 = s2;
            this.s3 = s3;
        }

        public double getS1() {
            return s1;
        }

        public double getS2() {
            return s2;
        }

        public double getS3() {
            return s3;
        }


    }
}

import java.util.Scanner;

public class Exercise_01 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter three sides of a triangle: ");
        double[] sides = new double[3];
        for (int i = 0; i < sides.length; i++) sides[i] = input.nextDouble();
        System.out.print("Enter a triangle color: ");
        String color = input.next();
        System.out.print("Is the triangle filled? true/false: ");
        String isFilledString = input.next();
        boolean isFilled = (isFilledString.equals("true"));

        Triangle t1 = null;
        try {
            t1 = new Triangle(sides[0], sides[1], sides[2]);
            t1.setColor(color);
            t1.setFilled(isFilled);
            System.out.println("Triangle 1:");
            System.out.println("Area = " + t1.getArea());
            System.out.println("Perimeter = " + t1.getPerimeter());
            System.out.println("Color = " + t1.getColor());
            System.out.println("Is filled? " + t1.isFilled());

        } catch (IllegalTriangleException e) {
            e.printStackTrace();
        }
    }
}

Friday, 21 October 2016

Chapter 10 Exercise 28, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

10.28 (Implement the StringBuilder class) The StringBuilder class is provided
in the Java library. Provide your own implementation for the following methods
(name the new class MyStringBuilder2):
public  MyStringBuilder2();
public MyStringBuilder2(char[] chars);
public MyStringBuilder2(String s);
public MyStringBuilder2 insert(int offset, MyStringBuilder2 s);
public MyStringBuilder2 reverse();
public MyStringBuilder2 substring(int begin);
public MyStringBuilder2 toUpperCase();

public class MyStringBuilder1 {

    private char[] buffer;
    public MyStringBuilder1(char[] chars) {
        buffer = new char[chars.length];

        System.arraycopy(chars, 0, buffer, 0, chars.length);
    }

    public MyStringBuilder1(String s) {
        this(s.toCharArray());
    }

    public MyStringBuilder1 append(int i) {

        String temp = "";
        while (i > 0) {
            temp = i % 10 + temp;
            i /= 10;
        }
        return new MyStringBuilder1(toString() + temp);
    }

    public MyStringBuilder1 append(MyStringBuilder1 s) {

        return new MyStringBuilder1(toString() + s.toString());
    }

    public String toString() {
        return new String(buffer);
    }

    public int length() {
        return buffer.length;
    }

    public char charAt(int i) {
        return buffer[i];
    }

    public MyStringBuilder1 toLowerCase() {
        char[] lower = new char[buffer.length];

        for (int i = 0; i < buffer.length; i++) {
            char old = buffer[i];
            if (old >= 'A' && old <= 'Z') {
                lower[i] = (char) (old - 'A' + 'a');
            } else {
                lower[i] = old;
            }
        }
        return new MyStringBuilder1(lower);
    }

    public MyStringBuilder1 substring(int begin, int end) {

        char[] temp = new char[end - begin];
        for (int i = begin; i < end; i++) {
            temp[i - begin] = buffer[i];
        }

        return new MyStringBuilder1(temp);
    }

    public MyStringBuilder1 insert(int offset, MyStringBuilder1 s) {
        char[] temp = new char[s.length() + buffer.length];
        for (int i = 0; i < offset; i++) {
            temp[i] = buffer[i];
        }

        for (int i = 0; i < s.length(); i++) {
            temp[offset + i] = s.charAt(i);

        }
        for (int i = offset + s.length(); i < temp.length; i++) {
            temp[i] = buffer[offset++];
        }

        return new MyStringBuilder1(temp);
    }

    public MyStringBuilder1 reverse() {
        char[] reverse = new char[buffer.length];

        int start = 0;
        for (int i = buffer.length - 1; i >= 0; i--) {
            reverse[i] = buffer[start++];
        }
        return new MyStringBuilder1(reverse);
    }

    public MyStringBuilder1 substring(int begin) {
        return substring(begin, buffer.length);
    }

    public MyStringBuilder1 toUpperCase() {

        char[] temp = new char[buffer.length];

        for (int i = 0; i < buffer.length; i++) {
            char ch = buffer[i];
            if (ch >= 'a' && ch <= 'z') {
                temp[i] = (char) (ch - 'a' + 'A');
            } else {
                temp[i] = ch;
            }
        }
        return new MyStringBuilder1(temp);
    }



}

public class Exercise_28 {

    public static void main(String[] args) {

        MyStringBuilder1 temp = new MyStringBuilder1("temp123");
        System.out.println("Current word = " + temp.toString());
        System.out.println("inserting INSERT at index 1: " + temp.insert(1, new MyStringBuilder1("INSERT")).toString());
        System.out.println("reverse temp123: " + temp.reverse().toString());
        System.out.println("to upper: " + temp.toUpperCase().toString());
    }
}

Chapter 10 Exercise 27, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

10.27 (Implement the StringBuilder class) The StringBuilder class is provided
in the Java library. Provide your own implementation for the following methods
(name the new class MyStringBuilder1):
public MyStringBuilder1(String s);
public MyStringBuilder1 append(MyStringBuilder1 s);
public MyStringBuilder1 append(int i);
public int length();
public char charAt(int index);
public MyStringBuilder1 toLowerCase();
public MyStringBuilder1 substring(int begin, int end);
public String toString();

public class MyStringBuilder1 {

    private char[] buffer;
    public MyStringBuilder1(char[] chars) {
        buffer = new char[chars.length];

        System.arraycopy(chars, 0, buffer, 0, chars.length);
    }

    public MyStringBuilder1(String s) {
        this(s.toCharArray());
    }

    public MyStringBuilder1 append(int i) {

        String temp = "";
        while (i > 0) {
            temp = i % 10 + temp;
            i /= 10;
        }
        return new MyStringBuilder1(toString() + temp);
    }

    public MyStringBuilder1 append(MyStringBuilder1 s) {

        return new MyStringBuilder1(toString() + s.toString());
    }

    public String toString() {
        return new String(buffer);
    }

    public int length() {
        return buffer.length;
    }

    public char charAt(int i) {
        return buffer[i];
    }

    public MyStringBuilder1 toLowerCase() {
        char[] lower = new char[buffer.length];

        for (int i = 0; i < buffer.length; i++) {
            char old = buffer[i];
            if (old >= 'A' && old <= 'Z') {
                lower[i] = (char) (old - 'A' + 'a');
            } else {
                lower[i] = old;
            }
        }
        return new MyStringBuilder1(lower);
    }

    public MyStringBuilder1 substring(int begin, int end) {

        char[] temp = new char[end - begin];
        for (int i = begin; i < end; i++) {
            temp[i - begin] = buffer[i];
        }

        return new MyStringBuilder1(temp);
    }

    public MyStringBuilder1 insert(int offset, MyStringBuilder1 s) {
        char[] temp = new char[s.length() + buffer.length];
        for (int i = 0; i < offset; i++) {
            temp[i] = buffer[i];
        }

        for (int i = 0; i < s.length(); i++) {
            temp[offset + i] = s.charAt(i);

        }
        for (int i = offset + s.length(); i < temp.length; i++) {
            temp[i] = buffer[offset++];
        }

        return new MyStringBuilder1(temp);
    }

    public MyStringBuilder1 reverse() {
        char[] reverse = new char[buffer.length];

        int start = 0;
        for (int i = buffer.length - 1; i >= 0; i--) {
            reverse[i] = buffer[start++];
        }
        return new MyStringBuilder1(reverse);
    }

    public MyStringBuilder1 substring(int begin) {
        return substring(begin, buffer.length);
    }

    public MyStringBuilder1 toUpperCase() {

        char[] temp = new char[buffer.length];

        for (int i = 0; i < buffer.length; i++) {
            char ch = buffer[i];
            if (ch >= 'a' && ch <= 'z') {
                temp[i] = (char) (ch - 'a' + 'A');
            } else {
                temp[i] = ch;
            }
        }
        return new MyStringBuilder1(temp);
    }



}

public class Exercise_27 {

    public static void main(String[] args) {

        MyStringBuilder1 s = new MyStringBuilder1("ButtonDemo");
        System.out.println(s.toString());
        System.out.println(s.append(100).toString());
        System.out.println(s.toString());
        System.out.println("lowercase = " + s.toLowerCase());
        System.out.println("substring 0 3: " + s.substring(0, 3));

    }
}

Chapter 10 Exercise 26, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

10.26 (Calculator)
Revise Listing 7.9, Calculator.java, to accept an expression as
a string in which the operands and operator are separated by zero
or more spaces. For example, 3+4 and 3 + 4 are acceptable expressions.

import java.util.ArrayList;

public class MyString1 {

    char[] chars;

    public MyString1(char[] chars) {

        this.chars = new char[chars.length];

        for (int i = 0; i < chars.length; i++)
            this.chars[i] = chars[i];


    }

    public MyString1(String string) {
        this(string.toCharArray());
    }

    public char charAt(int index)  {

        return chars[index];

    }

    public int length() {

        return chars.length;
    }

    public MyString1 substring(int begin, int end) {
        char[] s = new char[end - begin];
        for (int i = begin; i < end; i++) {
            s[i - begin ] = chars[i];
        }
        return new MyString1(s);
    }

    public MyString1 toLowerCase() {
        // A = 65
        // a = 97
        char[] lowerCase = new char[chars.length];

        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= 'A' && chars[i] <= 'Z') {
                lowerCase[i] = (char)(chars[i] + 32);
            } else {
                lowerCase[i] = chars[i];
            }
        }

        return new MyString1(lowerCase);

    }

    public boolean equals(MyString1 s) {

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != chars[i]) return false;
        }

        return true;
    }

    public static MyString1 valueOf(int i) {

        int length = getCount(i);
        char[] number = new char[length];
        for (int j = length - 1; j >= 0; j--) {
            number[j] = (char)('0' + (i % 10));
            i /= 10;
        }
        return new MyString1(number);
    }

    public static MyString1 valueOf(long i) {

        int length = getCount(i);
        char[] number = new char[length];
        for (int j = length - 1; j >= 0; j--) {
            number[j] = (char)('0' + (i % 10));
            i /= 10;
        }
        return new MyString1(number);
    }

    private static int getCount(long i) {
        int length = 0;
        while (i > 0) {
            i /= 10;
            length++;
        }
        return length;
    }

    public int compare(String s) {

        int limit = Math.min(s.length(), length());

        char[] chArray = s.toCharArray();
        int i = 0;
        while (i < limit) {
            char ch1 = charAt(i);
            char ch2 = chArray[i];
            if (ch1 != ch2) {
                return ch1 - ch2;
            }
            i++;
        }

        return length() - s.length();

    }

    public int compare(MyString1 s) {

        return compare(new String(s.toChars()));

    }
    public MyString1 substring(int begin) {
        return substring(begin, chars.length);
    }
    public MyString1 toUpperCase() {

        char[] temp = new char[chars.length];
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= 'a' && chars[i] <='z') {
                temp[i] = (char)(chars[i] - 32);
            } else {
                temp[i] = chars[i];
            }
        }

        return new MyString1(temp);
    }
    public char[] toChars() {
        return chars;
    }

    @Override
    public String toString() {
        return new String(chars);
    }

    public static MyString1 valueOf(boolean b) {
        return new MyString1((b) ? "true" : "false");
    }

    //  split("ab#12#453", "#") returns ab, #, 12, #, 453
    public static String[] split(String s, String regex) {

        if (isRegexArray(regex)) {
            return arraySplit(s, regex);
        } else {
            return wordSplit(s, regex);
        }

    }

    private static String[] wordSplit(String s, String regex) {

        ArrayList<String> temp = new ArrayList<>();

        int newIndex = 0;
        for (int i = 0; i < s.length() - regex.length(); i++) {

            if (regex.compareTo(s.substring(i, i + regex.length() )) == 0) {
                temp.add(s.substring(newIndex, i));
                temp.add(regex);
                newIndex = i + regex.length();
            }

        }
        temp.add(s.substring(newIndex, s.length()));
        return temp.toArray(new String[temp.size()]);
    }

    private static String[] arraySplit(String s, String regex) {
        char[] regexChars = getRegex(regex);

        ArrayList<String> temp = new ArrayList<>();
        int newIndex = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            for (int j = 0; j < regexChars.length; j++) {

                if (ch == regexChars[j]) {
                    if (newIndex != i)
                        temp.add(s.substring(newIndex, i));
                    temp.add("" + regexChars[j]);
                    newIndex = i + 1;
                }
            }
        }
        temp.add(s.substring(newIndex, s.length()));
        return temp.toArray(new String[temp.size()]);
    }

    private static char[] getRegex(String regex) {

        if (regex.charAt(0) != '[' && regex.charAt(regex.length() - 1) != ']')
            return regex.toCharArray();
        else
            return regex.substring(1, regex.length() - 1).toCharArray();

    }

    private static boolean isRegexArray(String regex) {
        return (regex.charAt(0) == '[' && regex.charAt(regex.length() - 1) == ']');
    }

}

public class Exercise_26 {

    public static void main(String[] args) {

        String temp = "";
        for (String s : args) {
            temp += s;
        }
        // Check number of strings passed
        args = MyString1.split(temp, "[+-/*]");
        if (args.length != 3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2");
            System.exit(0);
        }

        // The result of the operation
        int result = 0;

       // String[] array = MyString1.split()
        // Determine the operator
        switch (args[1].charAt(0)) {
            case '+':
                result = Integer.parseInt(args[0]) +
                        Integer.parseInt(args[2]);
                break;
            case '-':
                result = Integer.parseInt(args[0]) -
                        Integer.parseInt(args[2]);
                break;
            case '*':
                result = Integer.parseInt(args[0]) *
                        Integer.parseInt(args[2]);
                break;
            case '/':
                result = Integer.parseInt(args[0]) /
                        Integer.parseInt(args[2]);
        }

        // Display result
        System.out.println(args[0] + ' ' + args[1] + ' ' + args[2]
                + " = " + result);
    }
}