Showing posts with label Introduction to Java Programming. Show all posts
Showing posts with label Introduction to Java Programming. Show all posts

Monday, 13 March 2017

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

33.13 (Day of week) Write a program that displays the day of the week for a given day, month, and year, as shown in Figure 33.36. The program lets the user select a day, month, and year, and click the Get Day of Week button to display the day of week. The Time field displays Future if it is a future day or Past otherwise. Use the Zeller’s congruence to find the day of the week (See Programming Exercise 3.21).


import java.text.SimpleDateFormat;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.Date;

@ManagedBean
@SessionScoped
public class Exercise13 {
   public int day = 1;
   public int month= 1;
   public int year=2017;
   public String dayOfWeek="";
   public String time="";
   public int getDay() {
      return day;
   }

   public void setDay(int data) {
      this.day = data;
   }
   public int getMonth() {
      return month;
   }

   public void setMonth(int data) {
      this.month = data;
   }
   
   public int getYear() {
      return year;
   }

   public void setYear(int data) {
      this.year = data;
   }
   public String getSolution()
   {
       return "YES";
   }
   public String getdayOfWeek() {
        if ((month == 1)||(month == 2)) 
        {
            month += 12;
            year--;
 }
 int yearOfCentury = year % 100;
 int century = year / 100;  
        int cday = (day + (26 * (month + 1)) / 10 + yearOfCentury + yearOfCentury / 4 + century / 4 + 5 * century) % 7;
        switch(cday) 
        {
            case 0: dayOfWeek="Saturday"; break;
            case 1: dayOfWeek="Sunday"; break;
            case 2: dayOfWeek="Monday"; break;
            case 3: dayOfWeek="Tuesday"; break;
            case 4: dayOfWeek="Wednesday"; break;
            case 5: dayOfWeek="Thursday"; break;
            case 6: dayOfWeek="Friday"; break;
        }
      return dayOfWeek;
   }
   public String gettime()
   {
       Date now = new Date();
       SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
       try {
           Date date = dateFormat.parse(String.valueOf(year)+String.valueOf(month)+String.valueOf(day));
            if( now.compareTo( date) < 0 ) {
                time="Future";
            }
            else
            {
                time="Past";
            }
       }catch(Exception e)
       {
           
       }
       
       return time;
   }
   public void setdayOfWeek()
   {
       
   }

}

<?xml version = "1.0" encoding = "UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns = "http://www.w3.org/1999/xhtml" 
   xmlns:f = "http://java.sun.com/jsf/core"     
   xmlns:h = "http://java.sun.com/jsf/html"> 
   
   <head> 
      <title>Excercise 13</title> 
   </head> 
   
   <h:body> 
      <h2>Day Of Week Calculator</h2> 
      <hr /> 
      
      <h:form> 
         Day
         <h:selectOneMenu value = "#{exercise13.day}"> 
            <f:selectItem itemValue = '1' itemLabel = '1' /> 
            <f:selectItem itemValue = '2' itemLabel = '2' /> 
            <f:selectItem itemValue = '3' itemLabel = '3' /> 
            <f:selectItem itemValue = '4' itemLabel = '4' /> 
            <f:selectItem itemValue = '5' itemLabel = '5' /> 
            <f:selectItem itemValue = '6' itemLabel = '6' /> 
            <f:selectItem itemValue = '7' itemLabel = '7' /> 
            <f:selectItem itemValue = '8' itemLabel = '8' /> 
            <f:selectItem itemValue = '9' itemLabel = '9' /> 
            <f:selectItem itemValue = '10' itemLabel = '10' /> 
            <f:selectItem itemValue = '11' itemLabel = '11' /> 
            <f:selectItem itemValue = '12' itemLabel = '12' /> 
            <f:selectItem itemValue = '13' itemLabel = '13' /> 
            <f:selectItem itemValue = '14' itemLabel = '14' /> 
            <f:selectItem itemValue = '15' itemLabel = '15' /> 
            <f:selectItem itemValue = '16' itemLabel = '16' /> 
            <f:selectItem itemValue = '17' itemLabel = '17' /> 
            <f:selectItem itemValue = '18' itemLabel = '18' /> 
            <f:selectItem itemValue = '19' itemLabel = '19' /> 
            <f:selectItem itemValue = '20' itemLabel = '20' /> 
            <f:selectItem itemValue = '21' itemLabel = '21' /> 
            <f:selectItem itemValue = '22' itemLabel = '22' /> 
            <f:selectItem itemValue = '23' itemLabel = '23' /> 
            <f:selectItem itemValue = '24' itemLabel = '24' /> 
            <f:selectItem itemValue = '25' itemLabel = '25' /> 
            <f:selectItem itemValue = '26' itemLabel = '26' /> 
            <f:selectItem itemValue = '27' itemLabel = '27' /> 
            <f:selectItem itemValue = '28' itemLabel = '28' /> 
            <f:selectItem itemValue = '29' itemLabel = '29' /> 
            <f:selectItem itemValue = '30' itemLabel = '30' /> 
            <f:selectItem itemValue = '31' itemLabel = '31' /> 
         </h:selectOneMenu>
         Month
          <h:selectOneMenu value = "#{exercise13.month}"> 
              <f:selectItem itemValue = '1' itemLabel = 'January' /> 
              <f:selectItem itemValue = '2' itemLabel = 'February' /> 
              <f:selectItem itemValue = '3' itemLabel = 'March' /> 
              <f:selectItem itemValue = '4' itemLabel = 'April' /> 
              <f:selectItem itemValue = '5' itemLabel = 'May' /> 
              <f:selectItem itemValue = '6' itemLabel = 'June' /> 
              <f:selectItem itemValue = '7' itemLabel = 'July' /> 
              <f:selectItem itemValue = '8' itemLabel = 'August' /> 
              <f:selectItem itemValue = '9' itemLabel = 'September' /> 
              <f:selectItem itemValue = '10' itemLabel = 'October' /> 
              <f:selectItem itemValue = '11' itemLabel = 'November' /> 
              <f:selectItem itemValue = '12' itemLabel = 'December' />              
          </h:selectOneMenu>
         Year
         <h:inputText value="#{exercise13.year}" size="5"/>
         <h:commandButton value="Get Day of Week"/>
         <br />
         <p>
             Day of the Week <h:outputLabel value="#{exercise13.dayOfWeek}"/>
             Time <h:outputLabel value="#{exercise13.time}"/>
         </p>
         <br />
         
      </h:form>    
   
   </h:body> 
</html> 

Saturday, 11 March 2017

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

33.12(Game: the 24-point card game) Rewrite Exercise 20.17 using JSF, as shown in Figure 33.35. The program lets the user enter four card values and finds a solution upon clicking the Find a Solution button.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Exercise12 {
    private int[] numbers = new int[4];
    
    public Exercise12() {
        numbers[0] = 1;
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
    }
    
    
    public String getSolution() {
        Arrays.sort(numbers);
        String NumbersAsString = "";
        for (int i = 0; i < numbers.length; i++) {
                NumbersAsString += (char)(int)(numbers[i]);
        }
        String solution = displayPermutation(NumbersAsString);
        if(solution == null) {
                return "No solution";
        } else {
                return solution + " is 24";
        }  
    }
    
    public void setNumber0(int newNumner) {
        numbers[0] = newNumner;
    }
    
    public void setNumber1(int newNumner) {
        numbers[1] = newNumner;
    }
    
    public void setNumber2(int newNumner) {
        numbers[2] = newNumner;
    }
    
    public void setNumber3(int newNumner) {
        numbers[3] = newNumner;
    }
    
    public int getNumber0() {
        return numbers[0];
    }  
    
    public int getNumber1() {
        return numbers[1];
    }

    public int getNumber2() {
        return numbers[2];
    }
    
    public int getNumber3() {
        return numbers[3];
    }
    
    
    public String displayPermutation(String s) {
        return displayPermutation("", s);
    }

    public String displayPermutation(String s1, String s2) {
        if (s2.length() == 2) {
            String result = checkValue(s1 + s2.charAt(0) + s2.charAt(1));
            if (result != null) {
                return result;
            }
            result = checkValue(s1 + s2.charAt(1) + s2.charAt(0));
            if (result != null) {
                return result;
            }

        } else {
            for (int i = 0; i < s2.length(); i++) {
                String newS2 = "";
                for (int j = 0; j < s2.length(); j++) {
                    if (j != i) {
                        newS2 += s2.charAt(j);
                    }
                }
                String result = displayPermutation(s1 + s2.charAt(i), newS2);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

    public String checkValue(String value) {
        for (int i = 0; i < 4*4*4; i++) {
            int op1 = i % 4;
            int op2 = (i / 4) % 4;
            int op3 = (i / 16) % 4;
            String tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }

            tmp = "(" + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + ")" +  getValur(op2) + " " + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + "(" + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + ")" + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + " " +  getValur(op2) + "(" + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + ")";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = "(" + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + ")" +  getValur(op2) + "(" + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + ")";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }

            tmp = "(" + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + ")" + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + "(" + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + ")";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }


            tmp = "((" + (int)value.charAt(0) + " " + getValur(op3) + " " + (int)value.charAt(1) + ")" +  getValur(op2) + " " + (int)value.charAt(2) + ")" + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = "(" + (int)value.charAt(0) + " " + getValur(op3) + "(" + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + "))" + getValur(op1) + " " + (int)value.charAt(3) + " ";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + "((" + (int)value.charAt(1) + " " +  getValur(op2) + " " + (int)value.charAt(2) + ")" + getValur(op1) + " " + (int)value.charAt(3) + ")";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
            tmp = " " + (int)value.charAt(0) + " " + getValur(op3) + "(" + (int)value.charAt(1) + " " +  getValur(op2) + "(" + (int)value.charAt(2) + " " + getValur(op1) + " " + (int)value.charAt(3) + "))";
            if ((evaluateExpression(tmp) < 24.000001) && (evaluateExpression(tmp) > 23.999999)) {
                    return tmp;
            }
        }
        return null;
    }    
    
    public char getValur(int intValue) {
        switch (intValue) {
            case 0:
                return '+';
            case 1:
                return '-';
            case 2:
                return '*';
            default:
                return '/';
        }
    }    
    
    public static double evaluateExpression(String expression) {
        double result = 0;
        try {
            result = evaluateExpression(expression, null);
        } catch (Exception ex) {
        }
        return result;
    }
    
    public static double evaluateExpression(String expression, ArrayList<Integer> verifyNumbers) {
        if (expression.length() == 0) {
            return 0;
        }
        // Create operandStack to store operands
        Stack<Double> operandStack = new Stack<Double>();

        // Create operatorStack to store operators
        Stack<Character> operatorStack = new Stack<Character>();

        // Insert blanks around (, ), +, -, /, and *
        expression = insertBlanks(expression);

        // Extract operands and operators
        String[] tokens = expression.split(" ");

        // Phase 1: Scan tokens
        for (String token : tokens) {
            if (token.length() == 0) // Blank space
            {
                continue; // Back to the while loop to extract the next token
            } else if (token.charAt(0) == '+' || token.charAt(0) == '-') {
                // Process all +, -, *, / in the top of the operator stack
                while (!operatorStack.isEmpty()
                        && (operatorStack.peek() == '+'
                        || operatorStack.peek() == '-'
                        || operatorStack.peek() == '*' || operatorStack
                        .peek() == '/')) {
                    processAnOperator(operandStack, operatorStack);
                }

                // Push the + or - operator into the operator stack
                operatorStack.push(token.charAt(0));
            } else if (token.charAt(0) == '*' || token.charAt(0) == '/') {
                // Process all *, / in the top of the operator stack
                while (!operatorStack.isEmpty()
                        && (operatorStack.peek() == '*' || operatorStack.peek() == '/')) {
                    processAnOperator(operandStack, operatorStack);
                }

                // Push the * or / operator into the operator stack
                operatorStack.push(token.charAt(0));
            } else if (token.trim().charAt(0) == '(') {
                operatorStack.push('('); // Push '(' to stack
            } else if (token.trim().charAt(0) == ')') {
                // Process all the operators in the stack until seeing '('
                while (operatorStack.peek() != '(') {
                    processAnOperator(operandStack, operatorStack);
                }

                operatorStack.pop(); // Pop the '(' symbol from the stack
            } else { // An operand scanned
                // Push an operand to the stack
                try {
                    operandStack.push(new Double(token));
                    if (verifyNumbers != null) {
                        verifyNumbers.add(new Integer(token));
                    }
                } catch (NumberFormatException e) {
                    return 0;
                }
            }
        }

        // Phase 2: process all the remaining operators in the stack
        while (!operatorStack.isEmpty()) {
            processAnOperator(operandStack, operatorStack);
        }

        // Return the result
        if (operandStack.isEmpty()) {
            return 0;
        } else {
            return operandStack.pop();
        }
    }  
    
    /**
     * Process one operator: Take an operator from operatorStack and apply it on
     * the operands in the operandStack
     */
    public static void processAnOperator(Stack<Double> operandStack,
            Stack<Character> operatorStack) {
        char op = operatorStack.pop();
        double op1 = operandStack.pop();
        double op2 = operandStack.pop();
        if (op == '+') {
            operandStack.push(op2 + op1);
        } else if (op == '-') {
            operandStack.push(op2 - op1);
        } else if (op == '*') {
            operandStack.push(op2 * op1);
        } else if (op == '/') {
            operandStack.push(op2 / op1);
        }
    }

    public static String insertBlanks(String s) {
        String result = "";

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == ')' || s.charAt(i) == '+'
                    || s.charAt(i) == '-' || s.charAt(i) == '*'
                    || s.charAt(i) == '/') {
                result += " " + s.charAt(i) + " ";
            } else {
                result += s.charAt(i);
            }
        }

        return result;
    }    
}

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head>
        <title>Exercise12</title>
    </h:head>
    <h:body><h:form><center><br /><br />
        Enter four card values and click the button to determine<br />
        whether the four values has a 24-point solution<br />
        <br />
        <table><tr>
                <td width="50"><center><h:inputText value="#{exercise12.number0}" size="5"/></center></td>
                <td width="50"><center><h:inputText value="#{exercise12.number1}" size="5"/></center></td>
                <td width="50"><center><h:inputText value="#{exercise12.number2}" size="5"/></center></td>
                <td width="50"><center><h:inputText value="#{exercise12.number3}" size="5"/></center></td>
        </tr></table>
        <br /><p><font color = "#FF0000"><h:outputLabel value="#{exercise12.solution}"/></font></p><br />
        <h:commandButton value="Refresh"/>
    </center></h:form></h:body>
</html>