## Assignments

The most current assignment is posted first.

Note from the syllabus regarding collaboration on assignments: The purpose of this course is to learn the basics of programming and to that end, I do not consider it cheating to talk to other students in the course about HW problems and informally describe how a problem may be solved. Such collaborations are encouraged but must end when it comes time to code solutions.

# Final Project

Due: Monday Dec 12 by noon

Submit a zip with these things in it to the class submission page.

• Final Project Report: .doc or .pdf format.
• Project Code Instructions .doc or .pdf format
• Directory with your Project Code in it

Final Project Report
Roughly 3 Sections, 3 Pages of text single spaced (not counting references/pics), .doc or .pdf format.
1. What did you learn ∼ 1.5 pages
• Summary of the topic and analysis
2. Description of your deliverable ∼ 0.75 pages
• What does it do
• How does it work
• Ideas for improvement
3. Expectations vs Reality ∼ 0.75 pages
• Was writing project code harder/easier than you thought
• Did you meet your proposed goals
• If not, what happened
• What would you do differently on a similar project
Project Code Instructions
A word document or PDF called Instructions which gives instructions on how to compile and run your code.
Project Code
A directory with the code in it. If you used another environment for development such as NetBeans, Android Development Kit, or Visual Basic, do not include the environment in your submission. Just mention this in your instructions.

# Project Proposal

Due: Wednesday Nov 30
Posted: Mon Nov 28 09:54:55 CST 2011

See the Week 14, Lec 1 Slides for details on the project

3 sections, 1 page single spaced, Submit in .doc or .pdf format

1. What is being investigated
2. Why it is of interest to your group
3. Specific goals
• What do you want to
• Know when done
• Be able to do
• How you will demonstrate your know/do
• What is your deliverable, the code you will hand in

# Homework 6

Due: Tuesday Nov 22
Posted: Wed Nov 16 14:31:00 CST 2011

## Problem 1

Name your source file Polynomial.java and name the class Polynomial.

In HW 5 we wrote code to work with polynomials, but it used static methods so it was not object-oriented. We will create an object-oriented version here in the class Polynomial. We will then be able to create several polynomials.

### Variables/Fields (Internal data)

Only one private variable (field) is needed in class, double array of coefficients.

private double[] coefficients;
The internal array of coefficients. coefficients[0] is the smallest power coefficient (multiplied by $$x^0$$), coefficients[1]] is multiplied by $$x^1$$, and so forth.

### Constructors

Recall constructors allow for the creation of an object, possibly in different ways. Our Polynomial will have 2 constructors.

public Polynomial(double[] arr)
The coefficients for the polynomial are given in the array argument arr. Make a copy of arr and set the private variable coefficients to the copy.
public Polynomial(int n, Scanner s)
The polynomial will have degree $$n$$. Coefficients for the polynomial should be read from the Scanner argument s by using s.nextDouble(). $$n+1$$ coefficients need be be read. Create a double array and read the coefficients into it. You do not need to say new Scanner(...) as the scanner is given to you as an argument.

### Methods

public int degree()
Returns the degree of the polynomial. The lenght of the coefficients array is useful for this.
public double eval(double x)
Evaluate the polynomial at $$x$$. This will require looping over the coefficients array and summing the total.

### Stub

You may start your work using the stub below

import java.util.Scanner;
public class Polynomial{
// Put the coefficients private variable here

// Constructor: create from an array argument; make sure to copy arr
public Polynomial(double[] arr){
...;
}

// Constructor: read n+1 coefficients from Scanner s
public Polynomial(int n, Scanner s){
...;
}

// Return the degree of the polynomial
public int degree(){
...;
}

// Evaluate the polynomial at point x
public double eval(double x){
...;
}
}


### Driver

You may test your code with following driver. This file does not need to be modified.

import java.util.Scanner;
public class P1Driver {
public static void main(String[] args){
// Some x values to use
double[] xs = {1.0, 2.5, -3.1};

// Test the array constructor
double[] coefs1 = {1.5, 4.2, 9.3, -1};
Polynomial p1 = new Polynomial(coefs1);
// Test evaluation
for(int i=0; i<xs.length; i++){
System.out.printf("p1(%5.1f) = %10.2f\n",xs[i], p1.eval(xs[i]));
}

// Test the Scanner constructor
String input = "1.5 4.2 9.3 -1";
Scanner stringIn = new Scanner(input);
Polynomial p2 = new Polynomial(3,stringIn);
// Test evaluation
for(int i=0; i<xs.length; i++){
System.out.printf("p2(%5.1f) = %10.2f\n",xs[i], p2.eval(xs[i]));
}
}
}


## Problem 2

In class we discussed modelling a sheep farm. Many small farms diversify and keep multiple animals. We will model this.

In addition to keep sheep, alpacas will be kept on the farm. You will need to modify the Farm class to include the following fields and methods.

### Static Fields

• Alpacas cost $1000.00 initially • Alpacas cost$10.00 per day in upkeep
• Alpacas produce fur every 10 days
• Alpaca fur is worth $350.00 every time it is produced ### Instance fields • Each farm has a number of alpacas on it, call it alpacas • Each farm has a Strategy for buying alpacs, alpacaStrategy ### Modified Constructor public Farm(double initialMoney, int initialSheep, Strategy sheepStrat, int initialAlpacas, Strategy alpacaStrat) When created, farms get an initial number of sheep and alpacas with buying strategies for each. ### New Methods These methods are alpaca analogues to the respective sheep methods public void sellFur(int dayNumber) Like sellWool() public void buyAlpacas(int n) Like buySheep() ### Modified Methods These methods must be modified to account for the alpacas payUpkeep() Pay the upkeep for alpacas first, then for sheep so that sheep are starved first report() Include number of alpacas passDay() Add sellFur(), checks for alpacas, and buying of alpacas according to their strategy. ### Driver You can modify FarmDriver or use the driver below can be to test your code. public class FarmDriver2 { public static void main(String[] args){ Strategy[] sStrats = {new Strategy(1,1), new Strategy(1,5)}; Strategy[] aStrats = {new Strategy(1,15), new Strategy(1,25)}; int ndays = 30; for(int s=0; s<aStrats.length; s++){ System.out.printf("---TESTING STRATEGIES %d---\n",s); Farm f = new Farm(2000.00, 2, sStrats[s], 1, aStrats[s]); for(int i=1; i<=ndays; i++){ boolean alive = f.passDay(i); if(!alive){ System.out.printf("Failed at day %d\n",i); break; } } } } }  ## Problem 3 Put your sentence answers in a word document called Problem3.doc and your code in Problem3A.java and Problem3B.java . This is an analysis problem which will use your code from Problem 2. Write a driver called Problem3A.java which starts farms with initial conditions$1500, 2 sheep, and 2 alpacas. Find a strategy that will sustain the farm for 50 days.

• What are the strategies for sheep and alpaca buying?
• How much money is available after 50 days
• How many sheep and alpacas are alive after 50 days
• Include your driver Problem3A.java to prove your strategy produces these results.
• Modify the code to run for 300 days and save it as Problem3B.java.
• Does the same strategy work for 300 days?
• If not when does it fail?
• If so, how much money and how many animals exist after 100 days?

## Problem 4

This is a very crude model of a farm which does not account for many factors. Describe two additional factors which would be good to incorporate. For each factor, describe each of the following with 2-3 sentences.

• Why the factor is important to the problem
• What affects you would anticipate the factor would have on the farm
• How you incorporate the factor into a java simulation (e.g. classes and methods required)

# Homework 5

Due: Tuesday Nov 8
Updated: Mon Nov 7 22:33:59 CST 2011

HW 5 Solutions
1. Name your source file Problem1.java and name the class Problem1.

This problem tests your knowledge of 2D arrays.

Write code to read in an arbitrary sized matrix of integers. You will need to ask for two variables and at the beginning of the program and then create a by 2-dimensional array. Then read the elements into the 2D array. For ease of input, you may not want to prompt for each entry, just read an appropriate number of entries in using nextInt() in a loop. Print the matrix out at the end of your program.

Example with 4 rows, 3 columns (any number of rows and columns may be entered).

Enter number of rows and columns: 4 3
Enter 12 numbers in row order
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3
4 5 6
7 8 9
10 11 12

2. Name your source file Problem2.java and name the class Problem2.

This problem tests your ability to encapsulate code into a method.

Take the code that you wrote for Problem 1 and put it inside a method called int[][] readMatrix(int m, int n). The arguments to readMatrix are the number of rows and number of columns . The method creates the 2D array of integers, reads all entries into the appropriate array positions, and returns the result.

The main function of the Problem2 class prompts the user for the number of rows and columns, calls readMatrix to read in the matrix, and prints out the matrix returned by readMatrix.

Below is a stub of how the code should be arranged.

import java.util.Scanner;
public class Problem2{
public static void main(String[] args)  {
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter number of rows and columns: ");
int m = stdIn.nextInt();
int n = stdIn.nextInt();

// Print the matrix here
for(...){
for(...){
}
}

// Code to read in a matrix here
public static int[][] readMatrix(int m, int n){
Scanner stdIn = new Scanner(System.in);
...
}
}

3. Name your source file Problem3.java and name the class Problem3.

This problem tests your knowledge of 1D arrays and ability to write methods to modify them.

Write a method called rotate1() which rotates a 1D array of Strings by 1 position. An array rotation of 1 means element 0 becomes element 1, element 1 becomes element 2, etc. and element n-1 becomes element 0. An example is

String[] a = {"Amy", "Beth", "Chris", "Dan"};
rotate1(a);
// a is now {"Dan", "Amy", "Beth", "Chris"}


Note that rotation changes the oritinal array, it does not make a new copy.

Here is a stub

public class Problem3{
public static String[] rotate1(String[] a){
...
}
}


Do not include a main method in Problem3, only include the rotate1 method. Your code will be tested in a different class using the following general approach.

public class Problem3Driver{
public static void main(String[] args){
String[] s1 = {"alpha", "beta", "gamma"};
Problem3.rotate1(s1);
for(int i = 0; i < s1.length; i++){
System.out.printf("%s ",s1[i]);
}
System.out.println();

String[] s2 = {"All", "your", "bass", "are", "belong", "to", "us"};
Problem3.rotate1(s2);
for(int i = 0; i < s2.length; i++){
System.out.printf("%s ",s2[i]);
}
System.out.println();

}
}

4. Name your source file Problem4.java and name the class Problem4.

The problem deals with 1D arrays and method calls.

Recall our earlier work with polynomials on HW 1 and HW 3. Arrays make dealing with polyomials much easier as the coefficients can be stored in the array.

Write two methods in Problem4.java, one to read the coefficients of a polynomial from the user, and one to evaluate the polynomial at a specified value. The two methods will have the following prototypes:

• double[] readCoefficients(int n): is the degree of the polynomial to be read (e.g. 3 for ), so the method readCoefficients should read doubles and return them in an array. You may print a prompt for the coefficients, but this is not required.
• double evalPolynomial(double x, double[] coefficients): evaluate the polynomial represented by coefficients at the value x. You will need to loop to do this.

Do not include a main method in Problem4.java as you code will be tested in a driver like the one below.

import java.util.Scanner;
public class P4Driver {
public static void main(String[] args){
Scanner stdIn = new Scanner(System.in);
System.out.println("Problem4 class testing");

int n1 = stdIn.nextInt();
double x1 = stdIn.nextDouble();
double ans1 = Problem4.evalPolynomial(x1, coef1);
System.out.println("Value1" + ans1);

int n2 = stdIn.nextInt();
double x2 = stdIn.nextDouble();
double ans2 = Problem4.evalPolynomial(x2, coef2);
System.out.println("Value2" + ans2);
}
}

5. BONUS, worth 20-25% real extra credit for this assignment.

Name your source file Problem5.java and name the class Problem5.

This problem is made easier by using the replace() and replaceAll() methods of the String class which we did not cover in detail. You will need to review it on your own to complete the ex earn the extra credit.

The censor's bureau has determined that e-mail contains too much foul language and has hired you to help reduce the profanity. The purpose of the system is to analyze incoming text and if any words in appear in it that have been designated profanity, they are to be replaced with X's. The list of profane words is stored in an array but is subject to change. The initial list of words is defined as follows.

String[] profane = {
"hoser", "crap", "poopstain", "bumblebutt", "trolop", "turniphead"
};


To test part of the system, you are to write code which reads a sentence from the user and replaces all occurrences of such words with a number of X's equal to the lenght of the word. Here are 2 example runs with inputs and equivalent outputs given.

Enter a sentence:
That bumblebutt trolop is full of crap.
That XXXXXXXXXX XXXXXX is full of XXXX.

Enter a sentence:
My couch has a poopstain on it after that turniphead sat there.
My couch has a XXXXXXXXX on it after that XXXXXXXXXX sat there.


# Homework 4

Due: Monday Oct 17
Posted: Tue Oct 11 10:51:02 CDT 2011

HW 4 Solutions
1. Name your source file Problem1.java and name the class Problem1.

Do Exercise 2 on page 190 which concerns Stirling's formula for approximating large factorials. You should be able to do this using methods from the Math class.

2. Call your file Problem2.java and class Problem2.

Use the method System.out.printf() to print a table of information on the first 8 elements in the periodic table. You should not use a loop so 8 printf() statements will appear in your code.

You should draw information from Wikipedia for this. Here is an example of the output for elements 9-12.

 9  F   Fluorine 18.998
10 Ne       Neon 20.180
11 Na     Sodium 22.990
12 Mg  Magnesium 24.305


Specifically, the table should contain the following columns with a space between each column.

1. 2 characters wide: the atomic number of the element
2. 2 characters wide: the 2-letter chemical symbol
3. 10 characters wide: the full name of the element
4. 6 characters wide: the standard atomic weight to 3 decimal digits of accuracy. Make sure your code contains the full accuracy but use a the format specifier to print only 3 digits of the decimal.
3. (Harder) Name your file Problem3.java and name the class Problem3.

Implement a word count program. Prompt the user for a string and use the Scanner method nextLine() to read it in. Then use a loop to count the number of words that appear in the string. Words are separated by white space characters, so you can detect a word boundary by looping over the characters in the string, using the String method charAt() and the Character method isWhiteSpace() on the character to determine if it is whitespace. However, multiple spaces between two words should not change the word count. See the following example sessions:

Session 1

Enter string: Here are some words.
4 words


Session 2

Enter string:   has lots    of    spaces
4 words


Session 3

Enter string: So many words   I don't know what to do with   all of them.
13 words


## Homework 3

Due: Monday Oct 10
Mon Oct 3 12:42:30 CDT 2011

HW 3 Solutions
1. Name your source file Problem1.java and name the class Problem1.

Do Exercise 3 on page 145 which is to debug a program. Make sure to read the description of what the program is to do. Type it into DrJava and modify it so it behaves correctly.

2. Name your file ProductEvenInts.java as indicated by the class name in the exercise.

Exercise 5 on page 146. Copy the code from the textbook into DrJava and add in a loop to compute the product of even integers.

3. Exercise 6 on page 147, a trace problem. Write your trace in a Word Document called Problem3 or Problem3.docx.
4. Call your file Problem4.java and class Problem4

Translate the pseudocode in Figure 2.7 page 32 to java code. This algorithm asks for a favorite shape. If it is a circle, the user is asked for the radius and the area of the circle is printed.

Extend this algorithm in java so that if the favorite shape is a rectangle, the user is asked for the height and width and the area of the rectange is then printed. You wrote pseudcode for this part in HW1.

5. (Harder) Call your file Problem5.java and class Problem5.

We discussed pseudocode for evaluating the value of a polynomial in HW1. Convert this pseudocode into java using a loop. Refer to the answer key for HW1 if you need to.

## Homework 2

Due: Monday Sept 26
Posted: Mon Sep 19 10:33:03 CDT 2011

HW 2 Solutions
1. Write a java program that prompts for two input integers a and b, swaps them so that a has b's value and vice versa, then prints them both. A sample session:
Input a: 50
Input b: 22
New values are a = 22 and b = 50

2. Write a java program that reads two numbers and (decide what type they should be) and prints the result of the following numerical expression:
Input x: 1.25
Input y: 4.3
Expression = -26.476000

3. Write a java program that asks for 3 input words and prints out the last character of each input word.
Word 1: Oh
Word 2: goodness
Word 3: me
Last 3 letters: hse

4. The following code is intended to use the quadratic formula to solve quadratic equations. However, it is full of bugs. Use DrJava and your developing debugging skills to get it in working order. Note that it uses the Math.sqrt() function which we have not discussed, but this line does not contain any mistakes.
import java.util.Scanner;

public static void main(String[] args){
system.out.println("a x^2 + b x + c root finder");
Scanner stdIn = new Scanner(System.in);
System.out.print("Input a: ");
double a = stdIn.nextDouble();
System.out.print("Input b: ");
double b = stdIn.next();
System.out.print("Input c: ")
int c = stdIn.nextDouble();
double discriminant = Math.sqrt(b*b - 4*a*c);
double answer1 = (-b + discriminant) / (2 * a);
double answer2 = (-b - discriminant) / (2 * a;
}
}


An example session is below:

a x^2 + b x + c root finder
Input a: 1.5
Input b: -2.2
Input c: 0.1
Roots at 1.4197086760658 and 0.04695799060086673

5. Illustrate your knowledge of compound assignments by converting the following code to use compound assignment rather than conventional assignment. Note there are several spots where you should use the increment or decrement operator for full credit.
public class CompoundAssign{
public static void main(String[] args){
int i = 0;
i = i + 5;
i = i * 5;
i = i + 1;                  // Use the increment operator here
i = i + 1;                  // and here
System.out.println("i is " + i);

double d = 10.0;
d = d / 5.0;
d = d + 20.0;
d = d - 1.0;                // Use the decrement operator here
System.out.println("d is " + d);

String s = "A message";
s = s + " from me";
s = s + ", to you!";
System.out.println("s is '" + s + "'");
}
}


## Homework 1

Due: Monday Sept 12
Posted: Wed Aug 24 12:17:20 CDT 2011

Solutions for HW 1

Write answers to these problems in a text or Word document. Zip it and submit it at the course home page.

1. What are the 3 main parts of a computing system according to our discussion in class?
2. What kind of language does a modern computer understand?
3. What are the two main ways high level languages are made understandable by computers?
4. What are the units of size in computing and how large are they relative to one another?
5. Java is a hybrid system involving both compilation and interpretation.
• What are the two steps involved in executing a java program on a computer?
• What is the intermediate representation used by the java system called?
6. Give two examples of interpretation aside from java
• One from computing
• One not from computing
7. Extend the pseudocode example in Figure 2.7 on pg 32 to also compute the area of a
• Rectangle (explained earlier in the chapter)
• A regular hexagon: you'll need to search online to find out an appropriate parameter for input and the formula to use for area
8. Extend your algorithm from the previous problem to repeatedly ask the user for shapes using a loop. At each iteration of the loop, the user should be asked if they would like to compute the area of another shape. The program will only finish when the user answers "no" to this prompt.
9. Pg 53 #5, a trace problem.
10. (Harder) Write pseudocode that will evaluate a polynomial , and coefficients to . This will require a loop. Your first two inputs should be the value of and then degree . You should then prompt for each coefficient until all have been input and then print the value of the polynomial. You will need to track several things as your loop iterates such as the current value of and the current overall value of the polynomial to that point. At the end of the loop, the overall value of the polynomial should be printed.

The views and opinions expressed in this page are strictly those of the page author.
The contents of this page have not been reviewed or approved by the University of Minnesota.