Thursday, December 6, 2012

Java Chapter 3 Review

Review Questions

1. In Java, methods must include all of the following except a call to another method. (b)

2. All method declarations contain parentheses. (d)

3. A public static method named computeSum() is located in classA. To call the method from within classB, use the statement classA.computeSum(). (c)

4. Which of the following method declarations is correct for a static method named displayFacts() if the method receives an int argument? public static void displayFacts(int data) (c)

5. The method with the declaration public static int a Method(double d) has a method type of int. (b)
* The method type is its return type.

6. Which of the following is a correct call to a method declared as public static void aMethod(char code)? aMethod('Q');

7. A method is declared as public static void showResults(double d, int i). Which of the following is a correct method call? showResults(12.2, 67); (b)

8. The method with the declaration public static char procedure(double d) has a method type of char. (c)

9. The method public static boolean testValue(int response) returns a boolean value. (a)

10. Which of the following could be the last legally coded line of a method declared as public static int getVal (double sum)? return 77;

11. The nonstatic data components of a class often are referred to as the access types of that class. (a)

12. Objects contain methods and data items, which are also known as fields. (a)

13. You send message or information to an object through its methods. (b)

14. A program or class that instantiates objects of another prewritten class is a(n) client class. (a)

15. The body of a class is always written between curly braces. (c)

16. Most class data fields are private. (a)

17. The concepts of allowing a class's private data to be changed only by a class's own methods is known as information hiding. (c)

18. Suppose you declare an object as Book thisBook;. Before you store data in thisBook, you also must explicitly allocate memory for it. (a)

19. If a class is named Student, the class constructor name is Student. (d)

20. If you use the automatically supplied default constructor when you create an object, numeric fields are set to 0 (zero). (a)
Exercises
public class TestMethods
/* Introduction exercise to methods, do what the method identifiers state */
{
 public static void main(String[] args)
 {
  int valueOne = 1;
  int valueTwo = 2;

  displayIt(valueOne);
  displayIt(valueTwo);

  displayItTimesTwo(valueOne);
  displayItTimesTwo(valueTwo);

  displayItPlusOneHundred(valueOne);
  displayItPlusOneHundred(valueTwo);
 }

 public static void displayIt(int val)
 /* Displays the value */
 {
  System.out.println(val);
 }

 public static void displayItTimesTwo(int val)
 /* Multiplies value by 2 */
 {
  System.out.println(val * 2);
 }

 public static void displayItPlusOneHundred(int val)
 /* Adds 100 to the value */
 {
  System.out.println(val + 100);
 }
}
public class Numbers
{
 public static void main(String[] args)
 {
  int valueOne = 1;
  int valueTwo = 2;
  sum(valueOne, valueTwo);
  difference(valueOne, valueTwo);
 }

 public static void sum(int valOne, int valTwo)
 {
  System.out.println(valOne + " + " + 
   valTwo + " = " + (valOne + valTwo));
 }

 public static void difference(int valOne, int valTwo)
 {
  System.out.println(valOne + " - " + 
   valTwo + " = " + (valOne - valTwo));
 }
}
public class Numbers2
{
 public static void main(String[] args)
 {
  int valueOne = 1;
  int valueTwo = 2;
  sum(valueOne, valueTwo);
  difference(valueOne, valueTwo);
  int productResult = product(valueOne, valueTwo);
  System.out.println(valueOne + " * " + valueTwo + " = " +
   productResult);

 }

 public static void sum(int valOne, int valTwo)
 {
  System.out.println(valOne + " + " + 
   valTwo + " = " + (valOne + valTwo));
 }

 public static void difference(int valOne, int valTwo)
 {
  System.out.println(valOne + " - " + 
   valTwo + " = " + (valOne - valTwo));
 }

 public static int product(int valOne, int valTwo)
 {
  return (valOne * valTwo);
 }
}
import java.util.Scanner;

public class Eggs
{
 public static void main(String[] args)
 {
  int numberOfEggs;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter the number of eggs: ");
  numberOfEggs = keyBoard.nextInt();
  displayEggs(numberOfEggs);
 }

 public static void displayEggs(int eggs)
 {
  int dozens = eggs/12;
  int remainder = eggs % 12;
  System.out.println(eggs + " eggs is " + dozens + " dozens (with " +
   remainder + " eggs remaining)");
 }
}
import java.util.Scanner;

public class Exponent
{
 public static void main(String[] args)
 {
  int value;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter a value: ");
  value = keyBoard.nextInt();
  int valueSquared = square(value);
  int valueCubed = cubed(value);
  System.out.println(value + " squared is " + valueSquared);
  System.out.println(value + " cubed is " + valueCubed);
 }

 public static int square(int val)
 {
  return (val * val);
 }

 public static int cubed(int val)
 {
  return (val * val * val); 
 }
}
import java.util.Scanner;

public class Exponent2
{
 public static void main(String[] args)
 {
  int value;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter a value: ");
  value = keyBoard.nextInt();
  int valueSquared = square(value);
  int valueCubed = cubed(value);
  System.out.println(value + " squared is " + valueSquared);
  System.out.println(value + " cubed is " + valueCubed);
 }

 public static int square(int val)
 {
  return (val * val);
 }

 public static int cubed(int val)
 {
  return (square(val) * val); 
 }
}
import java.util.Scanner;

public class Calculator
{
 public static void main(String[] args)
 {
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter the price of the item: ");
  double priceOfItem = keyBoard.nextDouble();
  System.out.print("Enter the commission: ");
  double commission = keyBoard.nextDouble();
  System.out.print("Enter the customer rate discount: ");
  double discount = keyBoard.nextDouble();

  double finalPrice = calculateFinalPrice(priceOfItem, commission, discount);
  System.out.println("The final price is: " + finalPrice);
 }

 public static double calculateFinalPrice(double price, double salesCommission, double customerDiscount)
 {
  double priceWithCommission = price + (price * salesCommission);
  double totalDiscount= (customerDiscount * price);
  return (priceWithCommission - totalDiscount);
 }

}
import java.util.Scanner;

public class Divide
{
 public static void main(String[] args)
 {
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter first value: ");
  int valOne = keyBoard.nextInt();
  System.out.print("Enter second value: ");
  int valTwo = keyBoard.nextInt();
  Calculate (valOne, valTwo);
 }

 public static void Calculate(int first, int second)
 {
  int result = (first / second);
  int remainder = first % second;
  System.out.println(first + " / " + second + " = " + result +
   " with a remainder: " + remainder);
 }
}
import java.util.Scanner;

public class Salary
{
 public static void main(String[] args)
 {
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter hourly pay rate: ");
  double hourlyPayRate = keyBoard.nextDouble();
  System.out.print("Enter regular hours: ");
  int regularHours = keyBoard.nextInt();
  System.out.print("Enter overtime hours: ");
  int overtimeHours = keyBoard.nextInt();

  double totalPay = CalculateOvertimePay(hourlyPayRate, regularHours, overtimeHours);

  System.out.println("The total pay is: " + totalPay);
 }

 public static double CalculateOvertimePay(double hourlyRate, double regHours, double overtime)
 {
  double normalPay = (hourlyRate * regHours);
  double overtimePay = (overtime * (1.5 * hourlyRate));
  return (normalPay + overtimePay);
 }
}
import java.util.Scanner;

public class Interest
{
 public static void main(String[] args)
 {
  double val = GetStartingValue();
  double result = CalculateInvestment(val);
  System.out.println("After one year at 5% interest, you will have: $" +
   result);
 }

 public static double GetStartingValue()
 {
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter starting value of investment: ");
  double startingValue = keyBoard.nextDouble();
  return startingValue;
 }

 public static double CalculateInvestment(double val)
 {
  return (val * 1.05);
 }
}
public class Pizza
{
 private String toppings;
 private int diameter;
 private double price;

 public String getToppings()
 {
  return toppings;
 }
 public void setToppings(String top)
 {
  toppings = top;
 }

 public int getDiameter()
 {
  return diameter;
 }
 public void setDiameter(int dia)
 {
  diameter = dia;
 }
 
 public double getPrice()
 {
  return price;
 }
 public void setPrice(double pri)
 {
  price = pri;
 }
}
public class TestPizza
{
 public static void main(String[] args)
 {
  Pizza pie = new Pizza();
  pie.setPrice(14);
  pie.setToppings("Mushrooms");
  pie.setDiameter(20);
  System.out.println("Diameter is: " + pie.getDiameter());
  System.out.println("Toppings are: " + pie.getToppings());
  System.out.println("Price is: $" + pie.getPrice());
 }
}
public class Student
{
 private int id;
 private int numberOfCreditHours;
 private int numberOfPointsEarned;
 private double gPA;

 public Student()
 {
  id = 9999;
  numberOfCreditHours = 3;
  numberOfPointsEarned = 12;
 }

 public int getId()
 {
  return id;
 }
 public void setId(int identificationNumber)
 {
  id = identificationNumber;
 }

 public int getNumberOfCreditHours()
 {
  return numberOfCreditHours;
 }
 public void setNumberOfCreditHours(int creditHours)
 {
  numberOfCreditHours = creditHours;
 }

 public int getNumberOfPointsEarned()
 {
  return numberOfPointsEarned;
 }
 public void setNumberOfPointsEarned(int pointsEarned)
 {
  numberOfPointsEarned = pointsEarned;
 }

 public double calculateGPA()
 {
  return (numberOfPointsEarned / numberOfCreditHours);
 }
}
public class ShowStudent
{
 public static void main(String[] args)
 {
  Student a = new Student();
  a.setId(123);
  a.setNumberOfCreditHours(3);
  a.setNumberOfPointsEarned(12);
  System.out.println("ID is: " + a.getId());
  System.out.println("Credit hours: " + a.getNumberOfCreditHours());
  System.out.println("Points earned: " + a.getNumberOfPointsEarned());
  System.out.println("GPA is: " + a.calculateGPA());
 }
}
public class ShowStudent2
{
 public static void main(String[] args)
 {
  Student a = new Student();
  System.out.println("ID is: " + a.getId());
  System.out.println("Credit hours: " + a.getNumberOfCreditHours());
  System.out.println("Points earned: " + a.getNumberOfPointsEarned());
  System.out.println("GPA is: " + a.calculateGPA());
 }
}
public class Checkup
{
 private int patientNumber;
 private int bPS;
 private int bPD;
 private double lDL;
 private double hDL;

 public void setPatientNumber(int num)
 {
  patientNumber = num;
 } 
 public int getPatientNumber()
 {
  return patientNumber;
 }
 public void setBPS(int num)
 {
  bPS = num;
 } 
 public int getBPS()
 {
  return bPS;
 }
 public void setBPD(int num)
 {
  bPD = num;
 } 
 public int getBPD()
 {
  return bPD;
 }
 public void setLDL(double num)
 {
  lDL = num;
 } 
 public double getLDL()
 {
  return lDL;
 }
 public void setHDL(double num)
 {
  hDL = num;
 } 
 public double getHDL()
 {
  return hDL;
 }

 public void computeRatio()
 {
  System.out.println("The result is: " + (lDL/hDL));
 }

 public static void explainRatio()
 {
  System.out.println("HDL is known as the good cholesterol");
  System.out.println("A ratio of 3.5 or lower is considered optimum");
 }
}
import java.util.Scanner;

public class TestCheckup
{
 public static void main(String[] args)
 {
  Checkup firstPatient = new Checkup();
  Checkup secondPatient = new Checkup();
  Checkup thirdPatient = new Checkup();
  Checkup fourthPatient = new Checkup();
  firstPatient = getValues(firstPatient);
  showValues(firstPatient);
  secondPatient = getValues(secondPatient);
  showValues(secondPatient);
  thirdPatient = getValues(thirdPatient);
  showValues(thirdPatient);
  fourthPatient = getValues(fourthPatient);
  showValues(fourthPatient);
 }

 public static Checkup getValues(Checkup patient)
 {
  Scanner keyboard = new Scanner(System.in);
  System.out.print("Enter the patient number: ");
  patient.setPatientNumber(keyboard.nextInt());
  System.out.print("Enter the patient systolic BP: ");
  patient.setBPS(keyboard.nextInt());
  System.out.print("Enter the patient diastolic BP: ");
  patient.setBPD(keyboard.nextInt());
  System.out.print("Enter the patient LDL: ");
  patient.setLDL(keyboard.nextDouble());
  System.out.print("Enter the patient HDL: ");
  patient.setHDL(keyboard.nextDouble());
  return patient;
 }

 public static void showValues(Checkup patient)
 {
  System.out.println("The patient number is: " + patient.getPatientNumber());
  System.out.println("BP: " + patient.getBPS() + "/" + patient.getBPD());
  patient.computeRatio();
  patient.explainRatio();
 }
}
public class Invoice
{
 private int itemNumber;
 private String name;
 private int quantity;
 private double price;
 private double totalCost;

 public void setItemNumber(int num)
 {
  itemNumber = num;
 }
 public int getItemNumber()
 {
  return itemNumber;
 }
 public void setName(String nam)
 {
  name = nam;
 }
 public String getName()
 {
  return name;
 }
 public void setQuantity(int num)
 {
  quantity = num;
  recalculateTotalCost();
 }
 public int getQuantity()
 {
  return quantity;
 }
 public void setPrice(double num)
 {
  price = num;
  recalculateTotalCost();
 }
 public double getPrice()
 {
  return price;
 }
 public void recalculateTotalCost()
 {
  totalCost = (price * quantity);
 }
 public double getTotalCost()
 {
  return totalCost;
 }
 public void displayLine()
 {
  System.out.println("Item number: " + itemNumber);
  System.out.println("Name: " + name);
  System.out.println("Quantity: " + quantity);
  System.out.println("Price: " + price);
  System.out.println("Total cost: " + totalCost);
 }
}
import java.util.Scanner;

public class TestInvoice
{
 public static void main(String[] args)
 {
  Invoice invoice = new Invoice();
  invoice = getValues(invoice);
  invoice.displayLine();
 }

 public static Invoice getValues(Invoice inv)
 {
  Scanner keyboard = new Scanner(System.in);
  System.out.print("Enter item number: ");
  inv.setItemNumber(keyboard.nextInt());
  keyboard.nextLine();
  System.out.print("Enter item name: ");
  inv.setName(keyboard.nextLine());
  System.out.print("Enter quantity: ");
  inv.setQuantity(keyboard.nextInt());
  System.out.print("Enter the price: ");
  inv.setPrice(keyboard.nextDouble());
  return inv;
 }
}
public class Card
{
 private char suit;
 private int val;

 public void setSuit(char s)
 {
  suit = s;
 }

 public char getSuit()
 {
  return suit;
 }

 public void setVal(int v)
 {
  val = v;
 }

 public int getVal()
 {
  return val;
 }
}
import java.util.Random;

public class PickTwoCards
{
 public static void main(String[] args)
 {
  Cards firstCard = new Cards();
  firstCard = getCard(firstCard);
  Cards secondCard = new Cards();
  secondCard = getCard(secondCard);
  firstCard.setSuit('s');
  secondCard.setSuit('h');
  System.out.println("The first card");
  showCard(firstCard);
  System.out.println("The second card");
  showCard(secondCard);

 }

 public static Cards getCard(Cards aCard)
 {
  final int CARDS_IN_SUIT = 13;
  aCard.setVal(((int)(Math.random() * 100) % CARDS_IN_SUIT + 1));
  return aCard;
 }

 public static void showCard(Cards aCard)
 {
  System.out.println("suit: " + aCard.getSuit());
  System.out.println("value: " + aCard.getVal());
 }
}
public class MyCharacter
{
 private String color;
 private int eyes;
 private int lives;

 public String getColor()
 {
  return color;
 }
 public void setColor(String col)
 {
  color = col;
 }
 public int getEyes()
 {
  return eyes;
 }
 public void setEyes(int eye)
 {
  eyes = eye;
 }
 public int getLives()
 {
  return lives;
 }
 public void setLives(int life)
 {
  lives = life;
 }
}
import java.util.Scanner;

public class TwoCharacters
{
 public static void main(String[] args)
 {
  MyCharacter first = new MyCharacter();
  System.out.println("First character");
  first = design();
  MyCharacter second = new MyCharacter();
  System.out.println("Second character");
  second = design();
  System.out.println("First character");
  displayCharacters(first);
  System.out.println("Second character");
  displayCharacters(second);
 }

 public static MyCharacter design()
 {
  MyCharacter tempCharacter = new MyCharacter();
  Scanner keyboard = new Scanner(System.in);
  System.out.print("Enter color: ");
  tempCharacter.setColor(keyboard.nextLine());
  System.out.print("Enter number of eyes: ");
  tempCharacter.setEyes(keyboard.nextInt());
  System.out.print("Enter number of lives: ");
  tempCharacter.setLives(keyboard.nextInt());
  return tempCharacter;
 }

 public static void displayCharacters(MyCharacter character)
 {
  System.out.println("Color of character: " + character.getColor());
  System.out.println("Number of eyes: " + character.getEyes());
  System.out.println("Number of lives: " + character.getLives());
 }
}

Wednesday, December 5, 2012

Java Chapter 2 Review


Review Questions

1. When data cannot be changed after a class is compiled, the data is constant. (a)

2. Which of the following is not a primitive data type in Java? sector (d)

3. Which of the following elements is not required in a variable declaration? an assigned value (c)

4. The assignment operator in Java is = (a)

5. Assuming you have declared shoeSize to be a variable of type int, which of the following is a valid assignment statement in Java? shoeSize = 9; (a)

6. Which of the following data types can store a value in the least amount of memory? byte (d)

7. A boolean variable can hold the value true or false. (d)

8. The value 137.68 can be held by a variable of type Two of the preceding answers are correct. (d)

9. An escape sequence always begins with a(n) backslash (c)

10. Which Java statement produces the following output?
w
xyz

System.out.println("w\nxyz"); (c)

11. The remainder operator is none of the above. (d)

12. According to the rules of operator precedence, when division occurs in the same arithmetic statement as subtraction, the division operator always takes place first. (c)

13. The "equal to" relational operator is == (b)

14. When you perform arithmetic* with values of diverse types, Java implicitly converts the values to a unifying type. (b) *Typo, missing word: operations.

15. If you attempt to add a float, an int, and a byte, the result will be a(n) float. (a)

16. You use a type cast to explicitly override an implicit type. (b)

17. In Java, what is the value of 3 + 7 * 4 + 2? 33 (b)

18. What assignment is correct in Java? double value = 2.12; (c)

19. Which assignment is correct in Java? All of the above are correct. (d)

20. Which assignment is correct in Java? char aChar = '*'; (c)

Exercises

1.
a. 22
b. 14
c. 16
d. 8
e. 8.5
f. 5.6
g. 0
h. 1
i. 3
j. 10
k. 20
l. 4

2.
a. true
b. true
c. true
d. false
e. true
f. false
g. true
h. false
i. true
j. false

3.
a. int, no decimals
b. long, big number, cents are not important.
c. float, don't need too much accuracy, need decimal.
d. char, only need one character to represent initial.

public class Room
/* Computes the square foot of a room */
{
 public static void main(String[] args)
 {
  int length = 15;
  int width = 25;
  double area = (length * width);
  System.out.println("The floor space is " + area + " square feet.");
 }
}

import java.util.Scanner;

public class Room2
/* Computes the square foot of a room using user input */
{
 public static void main(String[] args)
 {
  int length;
  int width;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter the length of the room: ");
  length = keyBoard.nextInt();
  System.out.print("Enter the width of the room: ");
  width = keyBoard.nextInt();
  double area = (length * width);
  System.out.println("Here are the dimensions you entered");
  System.out.println("Length: " + length + " feet.");
  System.out.println("Width: " + width + " feet.");
  System.out.println("The floor space is " + area + " square feet.");
 }
}
public class Carpet
/* Computes the cost to cover an area with carpet */
{
 public static void main(String[] args)
 {
  int length = 15;
  int width = 25;
  double costPerSquareFoot = 3.25;
  int area = (length * width);
  double totalCost = (area * costPerSquareFoot);
  System.out.println("Here is a breakdown of the cost");
  System.out.println("Length: " + length + " feet");
  System.out.println("Width: " + width + " feet");
  System.out.println("Total area: " + area + " feet");
  System.out.println("Cost per square foot: $" + costPerSquareFoot);
  System.out.println("The total cost of covering a room of " + 
   area + " feet in carpet will be: $" + totalCost);
 }
}
import java.util.Scanner;

public class Carpet2
/* Computes the cost to cover an area with carpet using user input values*/
{
 public static void main(String[] args)
 {
  int length;
  int width;
  double costPerSquareFoot;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter length: ");
  length = keyBoard.nextInt();
  System.out.print("Enter width: ");
  width = keyBoard.nextInt();
  System.out.print("Enter price per square foot: $");
  costPerSquareFoot = keyBoard.nextDouble();
  int area = (length * width);
  double totalCost = (area * costPerSquareFoot);
  System.out.println("Here is a breakdown of the cost");
  System.out.println("Length: " + length + " feet");
  System.out.println("Width: " + width + " feet");
  System.out.println("Total area: " + area + " feet");
  System.out.println("Cost per square foot: $" + costPerSquareFoot);
  System.out.println("The total cost of covering a room of " + 
   area + " feet in carpet will be: $" + totalCost);
 }
}
public class Time
/* Computes hours and minutes worked from 
   the total amount of minutes worked */
{
 public static void main(String[] args)
 {
  final byte MINUTES_IN_ONE_HOUR = 60;
  int totalMinutesWorked = 197;
  int hoursWorked = totalMinutesWorked / MINUTES_IN_ONE_HOUR;
  int minutesWorked = totalMinutesWorked % MINUTES_IN_ONE_HOUR;
  System.out.println("Total time worked: " + hoursWorked 
   + " hours " + minutesWorked + " minutes");
 }
}
import java.util.Scanner;

public class Time2
/* Computes hours and minutes worked from the total 
   amount of minutes worked input from user */
{
 public static void main(String[] args)
 {
  final byte MINUTES_IN_ONE_HOUR = 60;
  int totalMinutesWorked;
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter total minutes worked: ");
  totalMinutesWorked = keyBoard.nextInt();
  int hoursWorked = totalMinutesWorked / MINUTES_IN_ONE_HOUR;
  int minutesWorked = totalMinutesWorked % MINUTES_IN_ONE_HOUR;
  System.out.println("Total time worked: " + hoursWorked 
   + " hours " + minutesWorked + " minutes");
 }
}
public class Initials
/* Display initials with a dot after each initial */
{
 public static void main(String[] args)
 {
  char firstInitial = 'A';
  char middleInitial = 'N';
  char lastInitial = 'M';
  System.out.println(firstInitial + "." +
   middleInitial + "." + lastInitial + ".");
 }
}
import java.util.Scanner;

public class Fees
/* Display student's total fees */
{
 public static void main(String[] args)
 {
  final byte PER_CREDIT_HOUR = 85;
  final byte ALTHETIC_FEE = 65;

  System.out.print("How many credit hours are you enrolled in: ");
  Scanner keyBoard = new Scanner(System.in);
  int numberOfCreditHoursEnrolled = keyBoard.nextInt();
  System.out.print("How much did you spend on books? $");
  double totalSpentOnBooks = keyBoard.nextInt();

  System.out.println("Here is a breakdown of the costs");

  System.out.println("Total Credit hours: " + numberOfCreditHoursEnrolled);
  System.out.println("Cost per credit hour: $" + PER_CREDIT_HOUR);
  double totalCostForCredits = (PER_CREDIT_HOUR * numberOfCreditHoursEnrolled);
  System.out.println("Total cost for credits: $" + totalCostForCredits);
  System.out.println("Total cost of books: $" + totalSpentOnBooks);
  System.out.println("Althetic fee: $" + ALTHETIC_FEE);

  double totalAmountDue = (totalCostForCredits + totalSpentOnBooks + ALTHETIC_FEE);

  System.out.println("Total amount due: $" + totalAmountDue);
 }
}
import java.util.Scanner;

public class Payroll
{
 public static void main(String[] args)
 {
  final float tax = 0.15F;

  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter your pay rate: ");
  float payRate = keyBoard.nextFloat();
  System.out.print("Enter number of hours worked: ");
  float hoursWorked = keyBoard.nextFloat();
  float grossPay = (hoursWorked * payRate);
  System.out.println("Your gross pay is: $" + grossPay);
  float withheldTax = (grossPay * tax);
  System.out.println("Total withheld tax: $" + withheldTax);
  float netPay = (grossPay - withheldTax);
  System.out.println("Total net pay: $" + netPay);
 }
}
import java.util.Scanner;

public class Dollars
/* Calculate dollars into currency demoninations */
{
 public static void main(String[] args)
 {
  Scanner keyBoard = new Scanner(System.in);
  System.out.print("Enter amount of dollars: $");
  int dollars = keyBoard.nextInt();

  int twenties = dollars / 20;
  System.out.println("20s: " + twenties);
  int tens = ((dollars % 20) / 10);
  System.out.println("10s: " + tens);
  int fives = ((dollars % 10) / 5);
  System.out.println("5s: " + fives);
  int ones = (dollars % 5);
  System.out.println("1s: " + ones);

 }
}
import java.util.Scanner;

public class FahrenheitToCelsius
/* Convert temperature from Fahrenheit to Celsius from user input Fahrenheit */
{
 public static void main(String[] args)
 {
  System.out.print("Enter temperature in Fahrenheit: ");
  Scanner keyBoard = new Scanner(System.in);
  double Fahrenheit = keyBoard.nextDouble();
  double Celsius = (Fahrenheit - 32) * 5/9;
  System.out.println("Fahrenheit: " + Fahrenheit);
  System.out.println("Celsius: " + Celsius);
 }
}
import javax.swing.JOptionPane;

public class TicketNumber
/* Identifies invalid ticket numbers */
{
 public static void main(String[] args)
 {
  String fullTicketString = JOptionPane.showInputDialog(null, "Ticket number", "Enter 6 digit ticket number", JOptionPane.QUESTION_MESSAGE);
  String lastDigit = fullTicketString.substring(fullTicketString.length() - 1);
  String trimTicketString = fullTicketString.substring(0, fullTicketString.lastIndexOf(lastDigit));
  int ticketNumber = Integer.parseInt(trimTicketString);
  int integerLastDigit = Integer.parseInt(lastDigit);
  boolean isValid = (ticketNumber % 7) == integerLastDigit;
  JOptionPane.showMessageDialog(null, isValid + "", "Validation", JOptionPane.INFORMATION_MESSAGE);
 }
}
import java.util.Scanner;

public class MadLib
/* Create a Mad Libs type game */
{
 public static void main(String[] args)
 {
  Scanner keyBoard = new Scanner(System.in);

  System.out.print("Enter a noun: ");
  String firstNoun = keyBoard.nextLine();

  System.out.print("Enter another noun: ");
  String secondNoun = keyBoard.nextLine();

  System.out.print("Enter an adjective: ");
  String adjective = keyBoard.nextLine();

  System.out.print("Enter a past-tense verb: ");
  String pastTenseVerb = keyBoard.nextLine();

  System.out.println("Mary had a little " + firstNoun);
  System.out.println("Its " + secondNoun + " was " + adjective + " as snow");
  System.out.println("And everywhere that Mary " + pastTenseVerb);
  System.out.println("The " + firstNoun + " was sure to go.");
 }
}

Friday, November 16, 2012

Java Chapter 1 Review

Java Programming 6th edition
Chapter 1: Review Questions

1. The most basic circuitry-level computer language, which consists of on and off switches, is machine language. (b)

2. Languages that let you use a vocabulary of descriptive terms, such as read, write, or add, are known as high-level languages. (a)

3. The rules of a programming language constitue its syntax. (d)

4. A compiler translates high-level language statements into machine code. (c)

5. Named computer memory locations are called variables. (b)

6. The individual operations used in a computer program are often grouped into units called procedures. (a)

7. Envisioning program components as objects that are similar to concrete objects in the real world is the hallmark of object-oriented programming (c).

8. The value of an object's attributes are also known as its state. (b)

9. An instance of a class is a(n) object. (a)

10. Java is architecturally neutral. (c)

11. You must compile classes written in Java into bytecode. (a)

12. All Java programming statements must end with semicolon. (c)

13. Arguments to methods always appear within parenthesis. (a).

14. In a Java program, you must use dots to separate classes, objects, and methods. (c)

15. All Java applications must have a method named main(). (b)

16. Nonexecuting program statements that provide documentation are called comments. (c)

17. Java supports three types of comments: line, block and javadoc. (a)

18. After you write and save a Java application file, you compile and then interpret it. (d)

19. The command to execute a compiled Java application is java. (d)

20. You save the text files containing Java source code using the file extension .java. (a)

Exercises (coming soon)

1.
a. weeklySales - legal
b. last character - illegal
c. class - illegal
d. MathClass - legal
e. myfirstinitial - legal
f. phone# - illegal
g. abcdefghiklmnop - legal
h. 23jordan - illegal
i. my_code - legal
j. 90210 - illegal
k. year2013budget - legal
l. abffraternity - legal

2.
a. TelevisionSet: size, make, numOfInputs
b. EmployeePaycheck: name, amount, department
c. PatientMedicalRecord: name, age, weight

3.
a. Politician: chrisChristie, mittRomney, barackObama
b. SportingEvent: superbowl, worldSeries, pGATour
c. Book: fightClub, oneFlewOverTheCuckoosNest, harryPotter

4.
a. mickeyMouse: Mouse, DisneyCharacter, Animal
b. myDogSpike: Dog, Animal, Pet
c. bostonMassachusetts: City, StateCapital, BaseballTeamHomeCity


public class Name
/*Displays my name*/
{
 public static void main(String[] args)
 {
  System.out.println("Name Line 1");
 }
}
public class Address
/*Displays my name and address*/
{
 public static void main(String[] args)
 {
  System.out.println("Address Line 1");
  System.out.println("Address Line 2");
  System.out.println("Address Line 3");
 }
}
public class Tree
/*Displays a tree pattern on the screen*/
{
 public static void main(String[] args)
 {
  System.out.println("   X   ");
  System.out.println("  XXX  ");
  System.out.println(" XXXXX ");
  System.out.println("XXXXXXX");
  System.out.println("   X   ");
 }
}
public class Initial
/*Displays my initials */
{
 public static void main(String[] args)
 {
  System.out.println("    AA     M     M");
  System.out.println("   A  A    M M M M");
  System.out.println("  AAAAAA   M  M  M");
  System.out.println(" A      A  M     M");
  System.out.println("A        A M     M");
 }
}
public class Diamond
/*Displays a Diamond */
{
 public static void main(String[] args)
 {
  System.out.println("  *  ");
  System.out.println(" * * ");
  System.out.println("* * *");
  System.out.println(" * * ");
  System.out.println("  *  ");
 }
}
//Displays the following comment:Program comments are nonexecuting statements you add to a file for the purpose of documentation.
/*Displays the following comment: Program comments are nonexecuting statements you add to a file for the purpose of documentation. */
/**Displays the following comment: Program comments are nonexecuting statements you add to a file for the purpose of documentation. */

public class Comments
{
 public static void main(String[] args)
 {
  System.out.println("Program comments are nonexecuting statements you add to a file for the purpose of documentation.");
 }
}
//Displays the following comment: Program comments are nonexecuting statements you add to a file for the purpose of documentation.
/*Displays the following comment: Program comments are nonexecuting statements you add to a file for the purpose of documentation. */
/**Displays the following comment: Program comments are nonexecuting statements you add to a file for the purpose of documentation. */

import javax.swing.JOptionPane;

public class CommentsDialog
{
 public static void main(String[] args)
 {
  JOptionPane.showMessageDialog(null, "Program comments are nonexecuting statements you add to a file for the purpose of documentation.");
 }
}
import javax.swing.JOptionPane;

public class BurmaShave
/*Displays a Burma Shave rhyme in a dialog box*/
{
 public static void main(String[] args)
 {
  JOptionPane.showMessageDialog(null, "Shaving brushes");
  JOptionPane.showMessageDialog(null, "You'll soon see 'em");
  JOptionPane.showMessageDialog(null, "On a shelf");
  JOptionPane.showMessageDialog(null, "In some museum");
  JOptionPane.showMessageDialog(null, "Burma Shave");
 }
}
public class CardLayout
/*Displays an attractive layout of information in a typical business card*/
{
 public static void main(String[] args)
 {
  System.out.println("Name Line 1");
  System.out.println("Address Line 1");
  System.out.println("Address Line 2");
  System.out.println("Home: Home Phone 1");
  System.out.println("Work: Home Phone 2");
 }
}
import javax.swing.JOptionPane;

public class RandomGuess
/* Guessing game where a user is challenged to guess a random number*/
{
 public static void main(String[] args)
 {
  JOptionPane.showMessageDialog(null, "Think of a number between 1 and 10.");
  JOptionPane.showMessageDialog(null, "Is it: " + (1 + (int)(Math.random()*10)));
 }
}

Tuesday, October 16, 2012

Javascript Denial of Service: Endless Alert

My professor is on a new language teaching streak it seems. From learning C in just a few days to now learning a bit of Javascript in a week. So here goes, our first task was to set up an endless alert.

So we have to create an HTML document with a script that keeps on opening a new dialog box once the previous one has been closed. When the dialog box is open, the user can't interact with the browser window at all... or so one would think. First let's think of a way to actually do this. It's pretty simple. We create an infinite loop with the alert box inside of the loop.

while (true)
{
alert ("Alert Message")
}


In order to make a script you have to use the script tag and assign the language the script will be using, in this case, Javascript. Then we come to the while statement, it will run infinitely because we have set the parameter to true at all times, it cannot be changed by any variable, because there is no variable to change.

Inside the while loop we have the "alert()" function. Inside of it's parenthesis we can put a message that will be displayed when the page is opened. In this case we used "Alert Message" just to test it out, but you can use any message you'd like to annoy the person that has unfortunately stumbled upon your website. Enjoy!

Just a note, this does have it's limitations, such as that it doesn't work well in Firefox 4. If the user receives a popup twice in a row, Firefox will inject a little check box that the user can check in order to stop the script from running. Another great feature with Firefox is that the user can interact with the outside environment, such as switching to other tabs or closing the current one.

Saturday, March 26, 2011

SyntaxHighlighter Review

I have finally managed to display source code correctly by using Syntax Highlighter. [1] I've gone through absolute hell to actually get this thing working though. I don't know much about HTML so you can imagine that I had quite a frustrating journey. I went through 6 different blogs which all showed different ways of installing it, none of them worked with blogger unfortunately. I finally found a blog that showed how to correctly install it on blogger.

Installation
The blog is called heisencoder [2], check it out if you'd like to learn how to install syntax highlighter on your blog too!

Demo

//code is displayed like this!


Impressions
It's nice, the code is displayed mostly correctly(see issues section). The code is displayed with line numbers, and alternating colors so you can separate one line from another.

It also has a "view plain" option integrated, this allows you to see the code in plain text and change around the source code before you print it. There is also a print feature, which if you click the print button, will print only the source code and ignore the rest of the blog. Which is awesome, no more parsing out the code, pasting it into notepad, and hitting print in order to save some trees. Finally there is a "?" option that will show you which version of SyntaxHighlighter the blogger is using, version 1.5.2 in my case.

Issues
Despite having it installed correctly, there are still some issues I have with SyntaxHighlighter. The first issue is with the actual code that it displays, if there are include statements in your code, it will insert HTML end tags as if the include statements were in HTML. Very frustrating to say the least, here is an example.


#include

As you can see it inserted a closing statement to my include stdio.h statement at the beginning of the program! It will do this with every include statement, so the more you have, the more bloated the code will look at the bottom. I noticed this problem doesn't happen on other blogging websites so it may be bloggers problem.

The other issue is with the pre tag, which must be included in order to separate the code from normal text, you must give it a name in quotations and a class type, also in quotations. I used C so the class would be "cpp". The name is where the problem arises, I tried naming a program "target3.c" and pasting the code between the pre tags. When the post was published, the code would be displayed as normal text as if ignoring SyntaxHighlighter completely! The solution that I found was to name everything "code" as this works every time.

That's all for now, I haven't played around with SyntaxHighlighter too much yet so if anything else comes up I'll be sure to post. I'm just glad I have a somewhat nice way to display source code.

EDIT: So I just found out I have an old version of SyntaxHighlighter, version 1.5.2. This may be the problem, I will look into updating the sources so that they point to an updated version. Until then, this is my short 1.5.2 SyntaxHighlighter review.

References
[1] http://alexgorbatchev.com/SyntaxHighlighter/
[2] http://heisencoder.net/2009/01/adding-syntax-highlighting-to-blogger.html

Tuesday, March 22, 2011

Reforming Credit Card Security

So for a midterm report, we had a choice between writing an ACM paper on reforming the social security number system, credit card security, or finding an exploit on school campus/computer system somehow. I went with the boring choice (I had about two days to complete it so I didn't want to travel to campus all the time), the credit card. Regardless, I came up with some really good ideas in my opinion. I wish I could just post the entire article here but it would probably be all screwed up thanks to the Blogger display setting. With this paper being an ACM paper, all my information is located there such as name, address, e-mail, phone number, and I really don't want people contacting me, unless it's through e-mail or comments of course :).

I'll give you a summary since you probably don't want to read my 4 page, single spaced paper as my writing is absolutely atrocious. I came up with two systems, one that would work when you're purchasing in store, and the other when you're purchasing online. These two systems would use different mechanics to accomplish the security.

While in a store this new system would use two biometric systems to accomplish the security. The first is a fingerprint scanner and the second is a camera. So one would slide the credit card across the reader, then to confirm ones identity, the potential customer would put his finger onto the scanner and at the same time have his picture taken by the camera (which would be integrated in the fingerprint scanner). This would replace the little signature pad that we are all used to and no one really pays attention to (especially the cashier), perhaps it would save a little time too. This ensures that the person is buying whatever is the owner of the card, if he or she isn't, then hopefully the fingerprint will be rejected. It's possible for the fingerprint scanner to be fooled however. [1] If it is, the camera is there to catch the face of the guilty suspect. If your card is stolen, then the store will have their fingerprint and/or picture for the authorities to use to track down the culprit. Although privacy is always a concern, the paper asked for security, not privacy.

Our online system uses a central credit card website such as VISA.com to hold all of your credit card information. If you want to purchase something from the internet, from Amazon for example, you must generate a code. This code is generated by giving VISA the total amount of the purchase ($52.69). VISA will generate a purchasing code using your account information and the amount. Once this is done, you can paste the code into Amazon's checkout section and pay Amazon the total amount or if you've made a mistake, it will either return the difference, or ask for more money before they ship the product. This ensures that only VISA has all of your information, it isn't stored anywhere else (such as Amazon, Barnes & Noble), etc. We could also employ a confirmation system by either mail or text message. Visa would alert you that you are about to make a purchase and you must either send back a confirmation or denial of payment.

The credit card is also redesigned. On the front, your name, expiration date, and bank logo are the only things that are listed, on the back is the familiar magnetic strip we are all used to. We don't need the account numbers on the front, they haven't been used since the manual credit card imprinter days. They also won't be necessary since we have the alternate online purchase method. The back of the card doesn't have the CCV number that also won't be necessary in our new system. The signature on the back to prove ownership and consent to the VISA terms and conditions is useless, you have your name on the front to prove ownership. The expiration date is to tell you when it's time to change cards as the magnetic strip wears out eventually through use.

My article goes into more depth than this and covers many other biometric devices that were looked at. If anyone really wants to take a look at it, please comment and I'll post it here albeit with identifying information removed.

References
[1] http://www.metacafe.com/watch/2350125/mythbusters_overcoming_a_fingerprint_security_system/

Blogger and Source Code

Blogger by itself is an abomination when it comes to posting code, it deletes my include statements outright and god knows what else it does! This means I'm on the desperate hunt for a new way to display source code on a website such as this. I'll be using this page to test various javascripts that I've found and see which one is the best or whichever actually accurately displays code.