## Wednesday, September 30, 2009

### Homework 4: Vectors A vector in 2-dimensional space, as used in math an physics, is just a pair of numbers: delta-x and delta-y. We call these numbers the components of the vector. Vectors are drawn as arrows. For example, the vector in the figure has a delta-x of 2, and a delta-y of 3. In physics, vectors represent forces. Adding two vectors represents placing those two forces on an object. The resulting force is just the addition of the two vectors. You can add two vectors by simply adding their delta-x and delta-y values. That is, the new delta-x is the sum of the delta-x of the two other vectors.
More formally, for vectors v1 and v2 with components v1.dx, v1.dy and v2.dx, v2.dy, we can define various vector operations:
• Vector addition: v1 + v2 = v3 is implemented as v3.dx = v1.dx + v2.dx and v3.dy = v1.dy + v2.dy
• Vector subtraction: v1 - v2 = v3 is implemented as v3.dx = v1.dx - v2.dx and v3.dy = v1.dy - v2.dy
• Vector scalar multiplication: v1 * c = v2 where c is a constant is implemented as v2.dx = v1.dx * c and v2.dy = v1.dy * c
• Vector magnitude of v1 is a number equal to the square root of v1.dx*v1.dx + v1.dy*v1.dy.
• A vector v1 can be normalized by setting v1.dx = v1.dx / v1.magnitude and v1.dy = v1.dy / v1.magnitude
For this homework you will implement a Vector class that has the following data members:
1. dx, a double
2. dy, a double
and the following methods:
1. A constructor that takes as argument two numbers which will become the delta-x and delta-y
2. public void addVector(Vector otherVector) which adds otherVector to this vector
3. public void subtractVector(Vector otherVector) which subtracts otherVector from this vector
4. public void multiply(int a) does a scalar multiplication of this vector by a
5. public double getMagnitude() returns the magnitude of this vector.
6. public void normalize() normalizes this vector.
7. public String toString() returns a printable version of the vector.

You must also implement a main function that tests all your methods to make sure they are correct.

One very important rule you must follow is Don't Repeat Yourself (DRY) which means that:

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system ”
In other words, any value that can be calculated from data member values must be calculated from data members values. This homework is due Tuesday, October 6 @ noon.

### lab test 1 demo for sec 6

import java.util.Scanner;

public class Labtest1demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i=0; i<input.length(); ++i)
{
if (i==0)
{
if (input.charAt(i)=='A' && input.charAt(i+1)==' ')
System.out.print("ONE");
else System.out.print(input.charAt(i));
}
else if (i==input.length()-1 && input.charAt(i)=='a' &&
input.charAt(i-1)==' ')
{
System.out.print("one");
}
else if (input.charAt(i)=='a' && input.charAt(i-1)==' ' &&
input.charAt(i+1)==' ')
{
System.out.print("one");
}
else System.out.print(input.charAt(i));
}

}

}



## Tuesday, September 29, 2009

### Test 1 Solutions and Grades

Below is our first test, along with the answers.
1. (10%) The following program fails to compile. Why does it fail to compile?
public class BrokenA {
public static final double RATE = 0.5;

public static void main(String[] args) {
double x = 0;
x = 10 * RATE;
RATE = 20;
}
}

Answer: Because we are trying to re-set the value of RATE which is a final variable.

2. (40%) What does the program below print when it runs?
import java.util.Scanner;

public class Mystery {

public static void main(String[] args) {
String sentence = "A rebel without a clue";
for (int i = 0; i < sentence.length(); i++){
char c = sentence.charAt(i);
int r = 0;
for (int j = 0; j < sentence.length(); j++){
if (sentence.charAt(j) == c)
r++;
}
System.out.println(c + ":" + r);
}
}

}

A:1
:4
r:1
e:3
b:1
e:3
l:2
:4
w:1
i:1
t:2
h:1
o:1
u:2
t:2
:4
a:1
:4
c:1
l:2
u:2
e:3


3. (50%) Write a program that:
1. Asks the user to enter any number of words. If the user enters the word done then the program ends. You can assume the user will always enter a word (he will not type in spaces, numbers, etc.)
2. After the user enters each word you will print out a score such that:
1. If a word has 9 or fewer letters the score is 2 times the number of letters.
2. If a word has 10 or more letters the score is 10 plus 2 times the number of letters.
3. If a word starts with the letter 'z' then it gets a score of 500, regardless of how many letters it has.
4. After the user enters done, you print out the longest word.

Below is a sample session:
Enter word:hello
Score=10
Enter word:howareyouthere
Score=38
Enter word:a
Score=2
Enter word:z
Score=500
Enter word:zoologically
Score=500
Enter word:done
The longest word was howareyouthere

import java.util.Scanner;

public class WordChecker {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String longest = "";
while  (true){
System.out.print("Enter word:");
String word = keyboard.next();
if (word.equalsIgnoreCase("done"))
break;
System.out.print("Score=");
if (word.substring(0,1).equalsIgnoreCase("z"))
System.out.println(500);
else if (word.length() > 10)
System.out.println(10 + 2*word.length());
else
System.out.println(2*word.length());
if (word.length() > longest.length())
longest = word;
}
System.out.println("The longest word was " + longest);
}
}


Below is the grade distribution for this test. The zeros are people who did not take the test. I will be handing back the tests on our next class.

### lab test 1

From a given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.

Example Input: " A boy is playing in a garden"

Example Output: " ONE boy is playing in one garden"

-- Not that 'A' and 'a' are to be replaced only when they are single characters, not as part of another word.

-- You cannot use "replace" or "replaceAll"

### Lab Test 01

For today's lab test, you need to write a Java program Calculator.java, that takes as input a simple mathematical expression and evaluates the expression. A simple mathematical expression contains two operands that will be input individually. You need to implement the addition, subtraction and multiplication on integers in your program. Note that the user input is NOT case sensitive, which means "Add" or "ADD" are all valid input. In addition, you need to count the number of completed calculations performed, and output this when the user quits the program.

Example Output

Welcome to the Calculator program.

Yi

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Enter the first number:

2

Enter the second number:

22

The value of 2 + 22 is:

24

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

multiply

Enter the first number:

3

Enter the second number:

5

The value of 3 * 5 is:

15

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Error: Addd is an invalid input

Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :

Exit

Yi completed 2 calculation.

Thank you for using the program. Goodbye.

File you must submit to xian@engr.sc.edu before the lab ends (29th, Sep. 4:00 pm):

Calculator.java

No late submission accepted!

Good luck!

### Chapter 6 Lecture

Below is the screencast for Chapter 6. In this chapter we talk about constructors, overloading, and static instance variables and member functions. All object-oriented programming languages implement concepts such as these. The goal of these is to make it easier for us to write large programs, even if it makes it a bit harder to write the tiny little programs we write in this class. You must have read chapter 6 and have watched the screencast before class on Thursday, October 1.

Also, below are the texbook's presenation slides for your reviewing pleasure.

## Thursday, September 24, 2009

### Lab 10

Question 13 on page 233.

Have fun!

## Tuesday, September 22, 2009

### Lab 9

Today's lab is the fizzbuzz problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

That is, the output should loook like:

1
2
Fizz
4
Buzz
Fizz
7
8
FizzBuzz
and so on...


Over at facebook they call this the Hoppity Hop problem.

### HW 3 Example

Below is my solution for the DNA homework. There are other ways to solve this problem.

import java.util.Scanner;

public class DNASearch {

static final int MAX_ERRORS = 1;

public static void main(String[] args){
String dna =
"ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCC" +
"CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGC" +
"CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGG" +
"AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCC" +
"CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAG" +
"TTTAATTACAGACCTGAA";

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter query:");
String query = keyboard.next();
for (int dnaIndex =0; dnaIndex < dna.length(); dnaIndex++){ //start comparing at every index
int numMatches = 0;
//calculate the number of matches between dna[dnaIndex to dnaIndex+query.lenth()] and query
for (int queryIndex = 0; queryIndex < query.length() && queryIndex + dnaIndex  < dna.length(); queryIndex++){
if (dna.charAt(dnaIndex + queryIndex) == query.charAt(queryIndex))
numMatches++;
}
if (numMatches >= query.length() - MAX_ERRORS){
System.out.println("Match at position " + dnaIndex);
}
}
}
}


## Monday, September 21, 2009

### HW2 example

import java.util.Scanner;

public class HW2Demo {

/**
* report bugs to xusun09@gmail.com
* other solutions are ok
*/
public static void main(String[] args) {

double tax=0;

if (income>5700 && income<=(5700+8350))
{
tax = (income-5700)*.1;
}
else if ((5700+8350)<income && income<=(5700+8350+33950))
{
tax = 8350*.1+(income-5700-8350)*.15;
}
else if ((5700+8350+33950)<income && income<=(5700+8350+33950+82250))
{
tax = 33950*.15+8350*.1+(income-5700-8350-33950)*.25;
}
else if ((5700+8350+33950+82250)<income &&
income<=(5700+8350+33950+82250+171550))
{
tax = 82250*.25+33950*.15+8350*.1+
(income-5700-8350-33950-82250)*.28;
}
else if ((5700+8350+33950+82250+171550)<income &&
income<=(5700+8350+33950+82250+171550+372950))
{
tax = 171550*.28+82250*.25+33950*.15+8350*.1+
(income-5700-8350-33950-82250-171550)*.33;
}
else if (income>372950)
{
tax = 171550*.33+171550*.28+82250*.25+33950*.15+8350*.1+
(income-5700-8350-33950-82250-171550-372950)*.35;
}

java.text.DecimalFormat df = new java.text.DecimalFormat("##.00");
tax = Double.parseDouble(df.format(tax));
System.out.println("Your taxes are $"+tax); } }  ## Thursday, September 17, 2009 ### Lab 08 Question 9 on page 232. Have fun! ## Tuesday, September 15, 2009 ### Homework 3: DNA The instructions for building any living organism is encoded in its DNA. We now have the ability to sequence (that is, get a full listing) of a person's DNA and look to see which particular genes that person carries, genes which might correspond to specific characteristics or diseases. A DNA sequence is a very long string composed only of the letters, A, C, G, T. For this homework you will use use following sample sequence: String dna = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCC" + "CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGC" + "CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGG" + "AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCC" + "CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAG" + "TTTAATTACAGACCTGAA";  Your program will ask the user for a query, which will be a combination of the letters ACGT, and you will program will then print out the index position (in the dna string) of all the places where that query matches. But, you will also need to allow for one character errors. That is, if there is only one letter difference, any letter, then the match should still count. Allowing for these errors is important in Biology because the DNA sequences do contain many errors because of limitations on the sequencing methods. Below are a few examples searches on the dna string above. The user types in the query and the program prints out the match positions. Enter query:ACAAGAT Match at position 0 Enter query:ACAAGAA Match at position 0 Enter query:CCTGGAGGG Match at position 70 Enter query:CCTGGGGGG Match at position 70 Enter query:ACAA Match at position 0 Match at position 96 Match at position 125 Match at position 131 Match at position 253 Match at position 270 Match at position 272 Match at position 315 Match at position 319 Match at position 321 Match at position 345 Match at position 357 Enter query:CCCCCCC Match at position 82 Match at position 243 Match at position 244 Match at position 245 Match at position 246  Hint: You will need to use a nested loop. This homework is due Tuesday, September 22 @noon. As always, email your program to your TAs. For Hackers only: If you feel this problem was too easy and want a little bit of a challenge, you can try to solve the welcome to code jam problem from the Google Code Jam 2009. It is similar to our problem but yet soooo much harder to solve. And, NO, you will not get any bonus points for solving it. If you can solve it, you should not be taking 145. You should be in 350. ### Lab 07 Write a program to read a list of words and to display the longest word (the one has longest length). The user indicates the end of the input by entering "done" (ignore cases). Example output: Please enter a list of words, enter "done" to stop: cat milk computer Hi java done The longest word is: computer Have fun! =) ### Chapter 5 Lecture Below is the screencast for the Chapter 5 lecture which is on classes and methods. Java is an object-oriented programming (OOP) language, as are C++, C#, Python, Ruby, and many other modern programming languages. OOPs all have classes, objects, and methods. Below are the slides for this chapter, for your review: You will need to have read Chapter 5 and have watched the screencast before class on Tuesday, September 22 ## Monday, September 14, 2009 ### Homework grading Base on my experience of grading homework 1, I got some explanations and requirements for the future homework. 0. Please use the format "CSCE145 - HW# - YOURNAME" as the subject. 1. Please send homework to Yi Xian (xian@engr.sc.edu)(SEC5 only) OR Xu Sun (xusun09@gmail.com)(SEC6 only). 2. Please send the .java file, NOT the .class file. 3. If you want to get full credits, please use the test cases provided in the homework descriptions to test your program before submitting it. 4. Your program should be able to executed at least(no syntax or grammar error). 5. If you sent a unfinished program, you will get very low credits or even 0. 6. If you modified or failed to handle any input format, you will lose credits, 1 or more. 7. If your program failed in any test cases, you will lose credits. 8. You can ask for the detailed reason why you lost credits for your homework in the lab session. ### HW1 example import java.util.Scanner; public class HW1Demo { /** * report bugs to xusun09@gmail.com */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Please enter the first 9 digits of the ISBN number:"); Scanner keyboard = new Scanner (System.in); String number = keyboard.nextLine(); number = number.replaceAll("-",""); int first = Integer.parseInt(number.substring(0, 1)); int second = Integer.parseInt(number.substring(1, 2)); int third = Integer.parseInt(number.substring(2, 3)); int fourth = Integer.parseInt(number.substring(3, 4)); int fifth = Integer.parseInt(number.substring(4, 5)); int sixth = Integer.parseInt(number.substring(5, 6)); int seventh = Integer.parseInt(number.substring(6, 7)); int eighth = Integer.parseInt(number.substring(7, 8)); int ninth = Integer.parseInt(number.substring(8, 9)); int tenth = 11 - (10*first + 9*second + 8*third + 7*fourth + 6*fifth + 5*sixth + 4*seventh + 3*eighth + 2*ninth)%11; System.out.println("The last digit is: " + tenth); } }  ## Thursday, September 10, 2009 ### lab 05 using only 2 comparisons import java.util.Scanner; public class lab05demo { /** * Another solution I mentioned in the lab * xusun09@gmail.com */ public static void main(String[] args) { Scanner reader = new Scanner(System.in); String s1 = reader.next(); String s2 = reader.next(); String s3 = reader.next(); if ((s1.compareTo(s2)>=0&&0>=s1.compareTo(s3))||(s1.compareTo(s2)<=0&&0<=s1.compareTo(s3))) { System.out.println(s1); } else if ((0>=s1.compareTo(s2)&&s1.compareTo(s2)>=s1.compareTo(s3))|| (0<=s1.compareTo(s2)&&s1.compareTo(s2)<=s1.compareTo(s3))) { System.out.println(s2); } else System.out.println(s3); } }  ## Wednesday, September 9, 2009 ### Lab 06 Question 8 on page 172. The option part is not required. ## Tuesday, September 8, 2009 ### Chapter 4 Lecture Below is the screencast for the Chapter 4 lecture. It is on loops: while and for loops. Every single programming language has while and for loops, and they always named 'while' and 'for', although the specific syntax of the for-loops can change a little bit between programming languages. You need to have read Chapter 4 and watched the screencast before class on Tuesday, September 15. Here are the slides from the textbook, for your reviewing needs: ### Homework 2: Taxes For this homework you will implement a program that calculates the federal taxes that a single person in the US must pay given her gross income. This homework is due Tuesday September 15 @noon. Like many countries, the US uses tax brackets to calculate the taxes a person must pay. The steps to calculate the tax amount are the following: (also see the wikipedia explanation) 1. Start with the gross income, subtract$5,700 from it. This is the new income value.
2. Use the table below and apply the various marginal tax rates depending on the person's new income value:
IncomeMarginal Tax Rate
<= $835010%$8,351– $33,95015%$33,951 – $82,25025%$82,251 – $171,55028%$171,551 – $372,95033%$372,951+35%

For example, if the income is $20,000, then we first subtract$5700 to get $14,300. Of this we have to pay 10% for the first$8,350, which works out to be $835, plus 15% of ($14,300 - $8,350) which is$892. So the total tax is $835 +$892 = $1,727. So, your program will ask the user to enter the income and then print out the tax, as such: Please enter income: 20000 Your taxes are$1727.


### lab 05

Question 3 on page 172. Have fun. =)

## Thursday, September 3, 2009

### Chapter 3 Lecture

Below is the screencast for Chapter 3 of the textbook. You should watch this lecture and read Chapter 3 before lecture on Tuesday, September 8. This chapter introduces loops: while and for loops. These are the most basic looping constructs and every programming language has them.

For your review, here are the textbook slides for chapter 3.

### Lab 04

Question 13 on page 118. Notes: you do NOT need to use JOptionPane I/O, console input/output will be fine. Have fun! =)

## Tuesday, September 1, 2009

### Homework 1: ISBN check digits Every book has an ISBN number. It is that number you see just above the bar code. For example, our textbook has an ISBN of 013607225-9. The dashes are not important, only the numbers matter.

Most importantly, the last number, known as a check digit, is computed from the first 10 digits using a specific equation. The wikipedia explains how:

A check digit is a form of redundancy check used for error detection, the decimal equivalent of a binary checksum. It consists of a single digit computed from the other digits in the message.

### ISBN-10

The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10 check digit — which is the last digit of the ten-digit ISBN — must range from 0 to 10 (the symbol X is used instead of 10) and must be such that the sum of all the ten digits, each multiplied by the integer weight, descending from 10 to 1, is a multiple of the number 11. Modular arithmetic is convenient for calculating the check digit using modulus 11. Each of the first nine digits of the ten-digit ISBN — excluding the check digit, itself — is multiplied by a number in a sequence from 10 to 2, and the remainder of the sum, with respect to 11, is computed. The resulting remainder, plus the check digit, must equal 11; therefore, the check digit is 11 minus the remainder of the sum of the products.

For example, the check digit for an ISBN-10 of 0-306-40615-? is calculated as follows:

s = 0×10 + 3×9 + 0×8 + 6×7 + 4×6 + 0×5 + 6×4 + 1×3 + 5×2
=    0 +  27 +   0 +  42 +  24 +   0 +  24 +   3 +  10
= 130
130 / 11 = 11 remainder 9
11 - 9 = 2

Thus, the check digit is 2, and the complete sequence is ISBN 0-306-40615-2.

Formally, the check digit calculation is: If the result is 11, a '0' should be substituted; if 10, an 'X' should be used.

The two most common errors in handling an ISBN (e.g., typing or writing it) are an altered digit or the transposition of adjacent digits. Since 11 is a prime number, the ISBN check digit method ensures that these two errors will always be detected. However, if the error occurs in the publishing house and goes undetected, the book will be issued with an invalid ISBN.

For this homework you will write a program which asks the users for the first 9 digits of the ISBN-10 number and then calculates and prints out the last digit. As such:

Enter 9-digit number: 0-13-607225
The last digit is 9

or
Enter 9-digit number: 013607225
The last digit is 9


Notice that your program must work even if the user enters the number with dashes, which he can place anywhere he wants.

The program is due by Tuesday, Sept. 8 @noon. When you are finished simply email the .java file to your TA, make sure you type CSCE145 in the Subject: line of your email. You should also cc: me in that email. The email must be sent by the deadline or you will not receive credit.

Finally, remember that you are bound by our Honor Code. Please, be responsible for your own work.

### Lab 03

Question 4 on page 116. Have fun!