Monday, 28 November 2016

Chapter 12 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

12.14 (Process scores in a text file)
Suppose that a text file contains an unspecified number of scores
separated by blanks. Write a program that prompts the user to enter
the file, reads the scores from the file, and displays their total
and average.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Exercise_14 {

    public static void main(String[] args) {

        // creating a random number of scores to test exercise
        int numberOfScores = (int) (Math.random() * 100 + 100);
        try {
            PrintWriter output = new PrintWriter("scores.txt");
            output.write(randomNumbers(numberOfScores));
            output.close();
            System.out.println("Saved " + numberOfScores + " scores to scores.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Scanner input = new Scanner(System.in);
        System.out.print("Enter filename: ");
        File filename = new File(input.next());
        input.close();

        if (!filename.exists()) {
            System.out.println(filename + " does not exist.");
            System.exit(1);
        }
        // Creating arrayList to hold an unspecified number of scores
        ArrayList<Integer> scores = new ArrayList<>();
        try {
            input = new Scanner(filename);
            while (input.hasNextInt()) {
                scores.add(input.nextInt());
            }
            System.out.println("Read " + scores.size() +" scores from " + filename);
        } catch (FileNotFoundException ex) {

            System.out.println("Error reading " + filename);
            ex.printStackTrace();
        }
    }

    public static String randomNumbers(int size) {

        String s = "";
        for (int i = 0; i < size; i++) {
            s += " " + (int) (Math.random() * 100);
        }

        return s;
    }
}

Chapter 12 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

12.13 (Count characters, words, and lines in a file)
Write a program that will count the number of characters,
words, and lines in a file. Words are separated by whitespace characters.
The file name should be passed as a command-line argument, as shown in Figure 12.13.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Exercise_13 {

    public static void main(String[] args) {

        if (args.length != 1) {
            System.out.println("Invalid arguments.");
            System.out.println("Usage: java Chapter_12.Exercise_13 filename");
            System.exit(1);
        }
        File filename = new File(args[0]);
        if (!filename.exists()) {
            System.out.println(filename + " does not exist.");
            System.exit(2);
        }

        int characters = 0;
        int words = 0;
        int lines = 0;

        try {
            Scanner input = new Scanner(filename);
            while (input.hasNext()) {
                String s = input.nextLine();
                lines++;
                characters += s.length();
                String[] split = s.split(" ");
                for (String word : split) {
                    words++;
                }
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        System.out.println("Characters: " + characters);
        System.out.println("Words: " + words);
        System.out.println("Lines: " + lines);


    }
}

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

(Reformat Java source code)
Write a program that converts the Java source code from the next-line brace
style to the end-of-line brace style. For example, the following Java source
in (a) uses the next-line brace style. Your program converts it to the end-of-line
brace style in (b).
Your program can be invoked from the command line with the Java sourcecode file
as the argument. It converts the Java source code to a new format.
For example, the following command converts the Java source-code file Test.java
to the end-of-line brace style.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Exercise_12 {

    public static void main(String[] args) {

        if (args.length != 1) {
            System.out.println("Invalid argument.");
            System.out.println("Usage: java Chapter_10.Exercise_12 Test.java");
            System.exit(1);
        }

        File filename = new File(args[0]);
        if (!filename.exists()) {
            System.out.println(filename + " does not exist.");
            System.exit(2);
        }

        StringBuilder buffer = new StringBuilder();
        try {
            Scanner input = new Scanner(filename);
            while (input.hasNext()) {
                String s = input.nextLine();

                if (s.contains("{")) {
                    buffer.append(" {");
                } else {
                    buffer.append("\n" + s );
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            PrintWriter output = new PrintWriter(filename);
            output.write(buffer.toString());
            output.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(buffer);
    }

    public static int getIndex(String s, char ch) {

        for (int i = 0; i < s.length(); i++) {
            if (ch == s.charAt(i)) {
                return i;
            }
        }
        return -1;
    }
}

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

12.11 (Remove text)
Write a program that removes all the occurrences of a specified string from a text file.
For example, invoking java Exercise12_11 John filename
removes the string John from the specified file.
Your program should get the arguments from the command line.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Exercise_11 {

    public static void main(String[] args) {

        if (args.length != 2) {
            System.out.println("Invalid arguments.");
            System.out.println("Usage: java Chapter_12.Exercise_11 word filename");
            System.exit(1);
        }

        // Check if the filename exist
        File filename = new File(args[1]);
        if (!filename.exists()) {
            System.out.println(args[1] + " does not exist.");
            System.out.println(2);
        }

        // create input and output files
        String s = "";
        try {
            Scanner input = new Scanner(filename);
            while (input.hasNext()) {
                s += input.nextLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        s = s.replaceAll(args[0], "");
        try {
            PrintWriter output = new PrintWriter(filename);
            System.out.println(s);
            output.write(s);
            output.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("Complete");
    }
}

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

12.10 (OutOfMemoryError)
Write a program that causes the JVM to throw an OutOfMemoryError and
catches and handles this error.


public class Exercise_10 {

    public static void main(String[] args) {

        try {
            int[] temp = new int[1000000000];
            temp = new int[temp.length * 1000000000];
        } catch (OutOfMemoryError ex) {
            ex.printStackTrace();
        }

    }
}

Chapter 12 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

12.9 (BinaryFormatException)
Exercise 12.7 implements the bin2Dec method to throw a BinaryFormatException
if the string is not a binary string. Define a custom exception called BinaryFormatException.
Implement the bin2Dec method to throw a BinaryFormatException if the string is not a binary string.


public class Exercise_09 {


    public static void main(String[] args) {

        System.out.println(bin2Dec("1100100"));
        // Purposely throwing an exception...
        System.out.println(bin2Dec("lafkja"));
    }

    public static int bin2Dec(String binary) throws BinaryFormatException {

        if (!isBinary(binary)) {
            throw new BinaryFormatException(binary + " is not a binary number.");
        }
        int power = 0;
        int decimal = 0;
        for (int i = binary.length() - 1; i >= 0; i--) {

            if (binary.charAt(i) == '1') {
                decimal += Math.pow(2, power);
            }
            power++;
        }
        return decimal;
    }

    public static boolean isBinary(String binary) {

        for (char ch : binary.toCharArray()) {
            if (ch != '1' && ch != '0') return false;
        }
        return true;
    }

}

class BinaryFormatException extends IllegalArgumentException {

    BinaryFormatException(String s) {
        super(s);
    }
}

Chapter 12 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

12.8 Exercise 12.6 implements the hex2Dec method to throw a NumberFormatException
if the string is not a hex string. Define a custom exception called HexFormatException.
Implement the hex2Dec method to throw a HexFormatException if the string is not a hex string.

import javafx.scene.control.TextField;

public class Kit {

    public static final int NOT_VALID = -1;


    public static String randomNumbers(int size) {

        String s = "";
        for (int i = 0; i < size; i++) {
            s += " " + (int) (Math.random() * 100);
        }

        return s;
    }

    public static Object[] getArray(Object... objects) {
        Object[] temp = new TextField[objects.length];
        for (int i = 0; i < objects.length; i++) {
            temp[i] = objects[i];
        }
        return temp;
    }

    public static String binaryFormat(String binaryString) {


        StringBuilder string = new StringBuilder(binaryString);


        int extraZeros = string.length() % 4;

        if (extraZeros != 0) {
            for (int i = 0; i < extraZeros; i++) {
                string.insert(0, "0");
            }
        }

        for (int i = string.length() - 1; i >= 0; i--) {

            if (i % 4 == 0 && i != 0) {
                string.insert(i, " ");
            }
        }

        return string.toString();

    }
    public static String hexToBinary(String hex) {

        return decimalToBinary(hexToDecimal(hex));
    }

    public static String decimalToBinary(long n) {

        StringBuilder stringBuilder = new StringBuilder();
        while (n > 0) {

            stringBuilder.insert(0, n & 1);
            n >>= 1;
        }

        return stringBuilder.toString();
    }

    public static String decimalToHex(long n) {

        StringBuilder stringBuilder = new StringBuilder();
        while (n > 0) {

            stringBuilder.insert(0, decimalToHexChar(n % 16));
            n /= 16;

        }

        return stringBuilder.toString();
    }
    public static long hexToDecimal(String hex) {

        if (!isHexadecimal(hex)) return NOT_VALID;

        long n = 0;

        int placeValue = hex.length() - 1;
        for (int i = 0; i < hex.length(); i++) {

            char ch = hex.charAt(i);

            if (isNumeric(ch)) {
                n += (charToDecimal(ch) * Math.pow(16, placeValue--));
            } else {
                n += hexLetterToInt(ch) * Math.pow(16, placeValue--);

            }
        }
        return n;
    }

    private static int hexLetterToInt(char ch) {

        ch = Character.toUpperCase(ch);

        return (ch - 'A' + 10);
    }

    /** returns Z is n is > 15 */
    private static char decimalToHexChar(long n) {

        if (n > 15) return 'Z';
        if (n > 9) return (char)(n % 10 + 'A');


        return (char)(n + '0');
    }
    public static long stringToDecimal(String s) {

        long n = 0;
        int placeValue =  s.length() - 1;

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

            int valid = charToDecimal(s.charAt(i));

            if (valid == NOT_VALID) return NOT_VALID;

            n += (Math.pow(10, placeValue--) * valid);

        }

        return n;
    }

    public static String decimalToString(long n) {

        StringBuilder s = new StringBuilder();

        while (n != 0) {

            s.insert(0, n % 10);
            n /= 10;
        }

        return s.toString();
    }

    public static int charToDecimal(char ch) {

        if (!isNumeric(ch)) return NOT_VALID;

        return ch - '0';

    }
    public static boolean isNumeric(String s) {

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

            if (!isNumeric(s.charAt(i))) return false;
        }

        return true;
    }
    public static boolean isNumeric(char ch) {

        return (ch >= '0' && ch <= '9');
    }

    public static boolean isHexadecimal(String s) {

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

            if (!isHexValid(s.charAt(i))) return false;
        }

        return true;
    }

    public static boolean isHexValid(char ch) {

        ch = Character.toUpperCase(ch);

        return isCharAtRange(ch, '0', '9') || isCharAtRange(ch, 'A', 'F');

    }


    public static boolean isCharAtRange(char ch, char start, char end) {

        return !(ch < start || ch > end);

    }

    public static int count(String str, char a) {

        int count = 0;
        for (int i = 0; i < str.length(); i++) {

            if (str.charAt(i) == a) count++;
        }

        return count;
    }

    public static void displayGrid(int[][] grid) {

        for (int[] aGrid : grid) {

            System.out.printf("%20s", "");
            for (int k = 0; k < aGrid.length; k++) {
                System.out.printf("|%-2d|", aGrid[k]);
            }
            System.out.println("");
        }

    }

    public static void displayGrid(int[] grid) {
        for (int i = 0; i < grid.length; i++) {

            System.out.printf("%-4d ", grid[i]);
            if ((i + 1) % 10 == 0)
            System.out.println("");
        }

    }

    public static void displayTimesTable(int x, int y) {
        // display 8x8 numbered grid to help solve exercise
        for (int i = 1; i <= y; i++) {

            System.out.printf("%20s", "");
            for (int k = 1; k <= x; k++) {
                System.out.printf("|%-2d|", i * k);
            }
            System.out.println("");
        }
    }

    public static int[] makeUnsortedArray(int size, int range) {
        int[] array = new int[size];

        for (int i = 0; i < array.length; i++) {
            array[i] = (int) (Math.random() * range + 1);
        }

        return array;
    }

    public static double[][] makeUnsortedArray(int rows, int columns, int range) {
        double[][] array = new double[rows][columns];

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {
                array[i][j] = (int) (Math.random() * range + 1);
            }
        }

        return array;
    }


    public static int[] merge(int[] list1, int[] list2) {

        int[] merge = new int[list1.length + list2.length];
        int m = 0, l1 = 0, l2 = 0;
        boolean l1isFinished = false;
        boolean l2isFinished = false;

        while (!l1isFinished || !l2isFinished) {

            if (l1 == list1.length) l1isFinished = true;
            if (l2 == list2.length) l2isFinished = true;
            if (l1isFinished && l2isFinished) break;

            if (!l1isFinished && l2isFinished) merge[m++] = list1[l1++];
            else if (!l2isFinished && l1isFinished) merge[m++] = list2[l2++];
            else if (list1[l1] <= list2[l2]) merge[m++] = list1[l1++];
            else if (list2[l2] <= list1[l1]) merge[m++] = list2[l2++];

        }
        return merge;
    }

    public static boolean isSorted(int[] numbers) {

        for (int i = 0; i < numbers.length - 1; i++) {

            if (numbers[i] > numbers[i + 1]) return false;

        }
        return true;
    }

    public static void displayMatrix(double[][] matrix) {
        for (double[] aMatrix : matrix) {

            for (int column = 0; column < aMatrix.length; column++) {
                System.out.printf("%5.0f ", aMatrix[column]);
            }
            System.out.printf("\n");
        }
    }

    public static void display(Object[] objects) {

        int count = 1;
        for (Object o : objects) {
            System.out.printf("%4s\n", o.toString());
            if (count % 10 == 0) {
                System.out.println("");
            }
            count++;
        }
    }
}

import java.util.Scanner;

public class Exercise_08 {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a string
        boolean isValid = false;
        String hex = "";
        int decimal = 0;
        while (!isValid) {
            try {
                System.out.print("Enter a hex number: ");
                hex = input.nextLine();
                decimal = hexToDecimal(hex);
                isValid = true;
            } catch (NumberFormatException ex) {
                System.out.println(ex.getLocalizedMessage());
                System.out.println("Try again...");
            }

        }
        System.out.println("The decimal value for hex number "
                + hex + " is " + decimal);
    }

    public static int hexToDecimal(String hex) throws HexFormatException {
        if (!Kit.isHexadecimal(hex)) {
            throw new HexFormatException("Not a hexadecimal number.");
        }
        int decimalValue = 0;
        for (int i = 0; i < hex.length(); i++) {
            char hexChar = hex.charAt(i);
            decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
        }

        return decimalValue;
    }

    public static int hexCharToDecimal(char ch) {
        if (ch >= 'A' && ch <= 'F')
            return 10 + ch - 'A';
        else // ch is '0' - '9'
            return ch - '0';
    }
}

class HexFormatException extends NumberFormatException {

    HexFormatException(String s) {
        super(s);
    }
}