CSCE 145: Algorithmic Design I
"abcde" "12345"then it should return a String with the value:
"a1b2c3d4e5"
/**
* Interleaves the letters of first and second. Assumes that first and second have the same length.
* @return the interleaved string
*/
public static String interleave(String first, String second){
String result = "";
for (int i =0; i < first.length(); i++){
result += first.substring(i, i+1) + second.substring(i,i+1);
}
return result;
}
long
values representing phone numbers and prints
out how many of those phone numbers are in Columbia (803),
Greenville (864), and Charleston (843). You must use a switch
statement in your method.n
as input:
long[] n = {8031234567l, 8649878787l, 8031223456l, 8034543212l, 8642323214l, 8432341231l};you will print out:
Columbia:3 Greenville:2 Charleston:1
public static void countAreaCodes (long[] phoneNumber){
int columbia = 0;
int greenville = 0;
int charleston = 0;
for (int i =0; i < phoneNumber.length;i++){
int areaCode = (int) (phoneNumber[i] / 10000000);
switch (areaCode) {
case 803:
columbia++;
break; //Don't forget the breaks!
case 864:
greenville++;
break;
case 843:
charleston++;
}
}
System.out.println("Columbia:" + columbia);
System.out.println("Greenville:" + greenville);
System.out.println("Charleston:" + charleston);
}
public class Enigma {
private static int x;
protected String s;
public Enigma(int x, String s){
System.out.println("Creating an Engima");
this.x = x;
this.s = s;
}
public void addItUp(int z){
x = x + z;
}
public void merge(Enigma e){
s = s + "+" + e.s;
}
public String toString(){
return "s=" + s + " x=" + Integer.toString(x);
}
}
public class Mystery extends Enigma {
private int y;
public Mystery (int x, int y, String s){
super(x,s);
System.out.println("Creating a Mystery");
this.y = y;
}
public void addItUp(int z){
y = y + z;
}
public String toString(){
return super.toString() + " y=" + Integer.toString(y);
}
}
public class Paradox extends Mystery {
public Paradox(int x, int y, String s) {
super(x, y, s);
System.out.println("Creating a Paradox");
}
public void merge (Paradox p){
s = "Do not cross the paradoxes!";
}
}
public class Main {
public static void main(String[] args) {
Paradox p = new Paradox (5,10,"This sentence is false");
Enigma e = new Enigma(33, "Black hole");
System.out.println(p);
System.out.println(e);
e.merge(p);
System.out.println(e);
p.merge(p);
System.out.println(p);
e.merge(p);
System.out.println(e);
p.addItUp(100);
System.out.println(p);
Enigma e2 = (Enigma)p;
e2.addItUp(500);
System.out.println(e2);
}
}
Creating an Engima Creating a Mystery Creating a Paradox Creating an Engima s=This sentence is false x=33 y=10 s=Black hole x=33 s=Black hole+This sentence is false x=33 s=Do not cross the paradoxes! x=33 y=10 s=Black hole+This sentence is false+Do not cross the paradoxes! x=33 s=Do not cross the paradoxes! x=33 y=110 s=Do not cross the paradoxes! x=33 y=610
1and this is a 4x4 diagonal matrix:
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1Implement a method that takes an integer n and returns an n x n array of integers that is a diagonal matrix.
public static int[][] makeDiagonalMatrix (int size){
int [][] result = new int[size][size];
for (int i = 0; i<size; i++ ){
result[i][i] = 1;
}
return result;
}
Tracker
which keeps track (in variables) of
toString() method has been called
toString()
invoked.public class Tracker {
private static int totalCount = 0;
private int count;
public Tracker(){
count = 0;
}
public String toString() {
count++;
totalCount++;
return "";
}
}
Exception
called
SilentException
such that a we do not have
to place within a try.catch
block a method that
throws SilentException
.
public class SilentException extends RuntimeException {
}
Order
, which has methods
(these exists, you don't have to write them):
boolean oversized()
: returns true if this order is for an oversized item.CARRIER getCarrier()
: where CARRIER is defined as enum CARRIER {UPS, FEDEX, USPS}
, returns the carrier. (A carrier is a company that ships packages. UPS, FEDEX, and USPS are the names of three different carrier companies.)boolean rush()
: return true if this a rush order.double
getShippingCosts(Order o)
and it will calculate the the
shipping and handling costs. The shipping costs for the different
carries are given in this table: UPS | FEDEX | USPS |
|
---|---|---|---|
Regular | $10 | $12 | $9 |
Oversized | $15 | $22 | $9 |
public static double getShippingCosts(Order o){
double basePrice = 0;
switch (o.getCarrier()) {
case UPS:
if (o.oversized())
basePrice = 15;
else
basePrice = 10;
break;
case FEDEX:
if (o.oversized())
basePrice = 22;
else
basePrice = 11;
break;
case USPS:
basePrice = 9;
}
if (o.rush())
basePrice = basePrice * 1.10;
basePrice += 4;
return basePrice;
}
String
input which represents a DNA sequence and
returns the index of the start of longest string of 'A' letters
in the sequence. If there are no A's then return -1. For example, /**
* This solution is good enough for 145*/
public static int longestRepeatA(String dna){
int longestIndex = -1;
int longestCount = 0;
for (int i =0; i < dna.length(); i++){
int lengthA = 0;
while (i + lengthA < dna.length() && dna.charAt(i+lengthA) == 'A'){
lengthA++;
};
if (lengthA > longestCount){
longestCount = lengthA;
longestIndex = i;
}
}
return longestIndex;
}
/** More experienced developers realize that the above is O(N^2) and that
* there is a way to implement it in linear time, like this: */
public static int longestRepeatB(String dna){
int longestIndex = -1;
int longestCount = 0;
int count = 0;
for (int i = 0; i < dna.length(); i++){
if (dna.charAt(i) == 'A') {
count++;
}
if (count > longestCount) {
longestCount = count;
longestIndex = i - count + 1;
}
if (dna.charAt(i) != 'A'){
count = 0;
}
}
return longestIndex;
}
double getAverageDropFourLowest(double [] grade)Assume that
grades.length >= 5
. For example, when given
double[] grade = {100,0,0,0,5,80,90};as input, your method should return
90.0Alert: Notice that this has to work when the lowest grades match, like in the example above where 3 of them where 0.
/** Returns an an array identical to grades but without the lowest number in grades dropped.
* if there are more than one minimum we only drop the first one.
* @param gradesthe array of grades
* @return a new array of size 1 less than grades.
*/
public static double[] dropMin(double [] grade){
double minval = grade[0];
double[] result = new double[grade.length - 1];
for (double i : grade){
if (i < minval)
minval = i;
}
int j = 0; //index into result
for (int i = 0; i < grade.length; i++){
if (j < i){ //already dropped min, so just copy the rest of the array
result[j++] = grade[i];
}
else if (grade[i] > minval) { //not the min
result[j++] = grade[i];
}
//if j==i and grades[i] == minval we do nothing, so i increases while j stays the same,
// thus ignoring this grade[i]
}
return result;
}
/** Returns the average after dropping the lowest 2 grades. */
public static double getAverageDropFourLowest(double [] grades){
double[] g = FinalTest.dropMin(grades);
g = FinalTest.dropMin(g);
g = FinalTest.dropMin(g);
g = FinalTest.dropMin(g);
double sum = 0;
for (double i : g){
sum += i;
}
return sum / (double) g.length;
}
public class MyExceptions {
public int trySomething(int x) throws Exception{
if (x < 0) {
throw new Exception("X is less than 0");
}
return 5;
}
public static void main(String[] args){
MyExceptions m = new MyExceptions();
try {
System.out.println("Starting");
int result = m.trySomething(10);
System.out.println("Got " + result);
result = m.trySomething(- 10);
System.out.println("Got " + result);
System.out.println("No more tries");
}
catch (Exception e){
System.out.println(e.getMessage());
}
System.out.println("Done");
}
}
Starting Got 5 X is less than 0 Done
catch
block? Would the program
compile or not? If you think it would not compile then explain
what the compiler complains about. If you think is would compile
then show what the program would print out when run.
try
without a catch
.
Employee
,
with data members String name
and int
salary
. Make sure that instances of your
Employee
can be written out to a binary file. But,
do not write the code to write instances to a file, just
make sure that instances of Employee
can be written
out to a binary file.
public class Employee implements Serializable {
private String name;
private int salary;
/** Add other methods, as needed. */
}
123432 3.14151 Ringowrite a program that reads those three values from the text file into an integer, double, and string variables, respectively.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class ReadFile {
public static void main (String[] args){
String fileName = "data.txt";
try {
Scanner inputStream = new Scanner(new File(fileName));
int i = inputStream.nextInt();
inputStream.nextLine();
double d = inputStream.nextDouble();
inputStream.nextLine();
String s = inputStream.next();
System.out.println("i=" + i + "\nd=" + d + "\ns=" + s);
}
catch (FileNotFoundException e){
System.out.println("File Not Found");
}
}
}
gcd
) of two numbers x and y is by using the following recursive definition of gcd(x,y)
:
the gcd(x,y) is equal to the gcd of y and x%y, the gcd(x,0) is equal to x.Implement a recursive function that calculates the greatest common division of any two integers.
public class GCD {
/** Calculate the greatest common division, using the recursive function:
gcd(x,y) = gcd(y,x%y)
gcd(x,0) = x */
public static int gcd (int x, int y){
if (y == 0)
return x;
return GCD.gcd(y, x%y);
}
public static void main (String[] args){
System.out.println(GCD.gcd(10,5));
System.out.println(GCD.gcd(10,1));
System.out.println(GCD.gcd(8,6));
System.out.println(GCD.gcd(121,11));
}
}
import java.util.ArrayList;
public class Test<Type, E>{
private ArrayList<Type> list;
private ArrayList<E> another;
public Test(){
list = new ArrayList<E>();
another = new ArrayList<E>();
}
public Type badFunction(E x, Type t){
E y = x;
Type tt = t;
list.add(t);
another.add("Alice");
Test<String,String> justMe = new Test<String,String>();
justMe.add("Bob", "Charlie");
return tt;
}
}
list = new ArrayList<E>();is wrong because the type
E
should be Type
as per the declaration of list
.
another.add("Alice");because we cannot assume that the type of
another
will be ArrayList<String>
.
The Towers of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
1. Only one disk may be moved at a time.
2. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
3. No disk may be placed on top of a smaller disk.
Below you will find a partial implementation of a Tower of Hanoi with two methods missing: getHeight and hanoi. For this test you will implement these methods.
--- the start Pole, destination Pole and the intermediate Pole are labeled A, B, C.
--- Each disk is labeled (from 1 to the n, n is the height of the tower)
--- Disk 1 is the smallest disk, and Disk n is the largest one.
Hint : The idea is that the method of moving n disks from start pole to destination pole is the same as the method of moving n-1 disks. For example, initially the tower has height 5, we must recursively move a tower of height 4 from A to C, move the biggest disk 5 from A to B (by simply calling method moveDisk), and finally recursively move the tower of height 4 to B from C.
public class HanoiTower {
static int moves = 0; //number of moves so far
/*Method getHeight is used to get the height of tower from user input*/
static int getHeight()
{
// TO DO
}
/*Method hanoi moves the tower of height n recursively
* it accept four arguments: the height of the current tower n, the fromPole, the toPole and the withPole.
* @param n the height of the current tower
* @param fromPole the start pole
* @param toPole the destination pole
* @param withPole the intermediate pole
* */
static void hanoi(int n, char fromPole, char toPole, char withPole)
{
// TO DO
}
/*Method moveDisk move the disk of diskLabel by simply printing on the console each move*/
static void moveDisk(int diskLabel, char fromPole, char toPole)
{
moves++;
System.out.println("steps: "+ moves);
System.out.println("Move " + diskLabel + " from " + fromPole + " to " +toPole);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int TowerHeight;
char FromPole='A', ToPole='B', WithPole='C';
System.out.println("Please Enter Tower height...");
TowerHeight = getHeight();
hanoi(TowerHeight, FromPole, ToPole, WithPole);
}
}
Here is the output of height of 3 after you properly implement the methods:
Please Enter Tower height...
3
steps: 1
Move 1 from A to B
steps: 2
Move 2 from A to C
steps: 3
Move 1 from B to C
steps: 4
Move 3 from A to B
steps: 5
Move 1 from C to A
steps: 6
Move 2 from C to B
steps: 7
Move 1 from A to B
Notes:
Submit your HanoiTower.java file to espiggy@gmail.com before 4:00pm. No late submission accepted!
Hint:
here is the code of class Spices .
import java.util.Scanner;
/**
Class for data on endangered species.
*/
public class Species
{
private String name;
private int population;
private double growthRate;
public void readInput( )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the species' name?");
name = keyboard.nextLine( );
System.out.println(
"What is the population of the species?");
population = keyboard.nextInt( );
while (population < 0)
{
System.out.println("Population cannot be negative.");
System.out.println("Reenter population:");
population = keyboard.nextInt( );
}
System.out.println("Enter growth rate (% increase per year):");
growthRate = keyboard.nextDouble( );
}
public void writeOutput( )
{
System.out.println("Name = " + name);
System.out.println("Population = " + population);
System.out.println("Growth rate = " + growthRate + "%");
}
/**
Precondition: years is a nonnegative number.
Returns the projected population of the calling object
after the specified number of years.
*/
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
public void setSpecies(String newName, int newPopulation,
double newGrowthRate)
{
name = newName;
if (newPopulation >= 0)
population = newPopulation;
else
{
System.out.println("ERROR: using a negative population.");
System.exit(0);
}
growthRate = newGrowthRate;
}
public String getName( )
{
return name;
}
public int getPopulation( )
{
return population;
}
public double getGrowthRate( )
{
return growthRate;
}
public boolean equals(Species otherObject)
{
return (name.equalsIgnoreCase(otherObject.name)) &&
(population == otherObject.population) &&
(growthRate == otherObject.growthRate);
}
}
Here is the code from Listing 12.5 on Page 821.
public class StringLinkedListSelfContained
{
private ListNode head;
public StringLinkedListSelf( )
{
head = null;
}
/**
Displays the data on the list.
*/
public void showList( )
{
ListNode position = head;
while (position != null)
{
System.out.println(position.data);
position = position.link;
}
}
/**
Returns the number of nodes on the list.
*/
public int length( )
{
int count = 0;
ListNode position = head;
while (position != null)
{
count++;
position = position.link;
}
return count;
}
/**
Adds a node containing the data addData at the
start of the list.
*/
public void addANodeToStart(String addData)
{
head = new ListNode(addData, head);
}
/**
Deletes the first node on the list.
*/
public void deleteHeadNode( )
{
if (head != null)
head = head.link;
else
{
System.out.println("Deleting from an empty list.");
System.exit(0);
}
}
/**
Sees whether target is on the list.
*/
public boolean onList(String target)
{
return find(target) != null;
}
// Returns a reference to the first node containing the
// target data. If target is not on the list, returns null.
private ListNode find(String target)
{
boolean found = false;
ListNode position = head;
while ((position != null) && !found)
{
String dataAtPosition = position.data;
if (dataAtPosition.equals(target))
found = true;
else
position = position.link;
}
return position;
}
public String[] toArray( )
{
String[] anArray = new String[length( )];
ListNode position = head;
int i = 0;
while (position != null)
{
anArray[i] = position.data;
i++;
position = position.link;
}
return anArray;
}
private class ListNode
{
private String data;
private ListNode link;
public ListNode( )
{
link = null;
data = null;
}
public ListNode(String newData, ListNode linkValue)
{
data = newData;
link = linkValue;
}
}
}
public class BinarySearchTree {
private BinarySearchTree left;
private BinarySearchTree right;
private int data;
public BinarySearchTree() {
left = null;
right = null;
}
/** Create a tree that consists of just one node with no children. */
public BinarySearchTree(int data) {
left = null;
right = null;
this.data = data;
}
/** Adds new number n to this BinarySearchTree, placing it in its correct place.
*
* @param n the number to be added
*/
public void add (int n) {
if (n <= data) {
if (left != null)
left.add(n);
else
left = new BinarySearchTree(n);
}
else { // n > data
if (right != null)
right.add(n);
else
right = new BinarySearchTree(n);
}
}
/** Returns the maximum number in this tree. */
public int max() {
if (right == null)
return data;
return right.max();
}
/** Returns the height of this tree. */
public int height() {
//The base cases are when a child is null.
return 1 + Math.max((left == null ? 0: left.height()),
(right == null ? 0: right.height()));
}
}
For this homework you will implement a simple generic Set class. That is, you will implement a class Set<T>
using Java's ArrayList
as the data member that holds the values.
A set is defined as a collection of elements (in our case, all of the same type) such that every element appears at most once in the collection. The methods your Set<T>
must implement are:
Set()
the constructor takes no arguments and creates an empty set.String toString()
returns a string with all the elements of this set in printed form, as usual.void add(T x)
adds element x
to the set. If x
is already in the set then it does nothing.boolean contains(T x)
returns true if the set contains the element x
, false otherwise.void add(Set<T> other)
adds the complete contents of the set other
to this set.void subtract(Set<T> other)
removes every element of other
that is in this set.boolean isSubset(Set<T> other)
returns true if and only if this set is a subset of other
, that is, if all the elements in this set are also contained in other
.You will also implement some test cases in your main()
to ensure that your class works correctly. This homework is due on Tuesday, November 24 @noon.
CSCE 145: Chapter 12 from Jose Vidal on Vimeo.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Scanner;
public class Notebook {
private Reading[] reading;
private int nextIndex = 0;
/** Maximum number of readings. */
private static final int SIZE = 100;
public Notebook(){
reading = new Reading[SIZE];
}
/**
* Creates a notebook by reading its contents from the given file.
* @param filename
* @throws IOException
*/
public Notebook(String filename) throws IOException {
try {
ObjectInputStream input = new ObjectInputStream (new FileInputStream(filename));
nextIndex = input.readInt();
reading = (Reading[])input.readObject();
input.close();
} catch (ClassNotFoundException e) {
System.out.println("ERROR: File corrupted.");
e.printStackTrace();
}
}
/**
* Adds a reading to the notebook
* @param species name of the species
* @param count how many you saw
* @param comment
* @throws Exception if the notebook gets too big
*/
public void addReading(String species, int count, String comment) throws Exception{
//The right thing to do is use a data structure that expands as needed, but that's CSCE 146
// so we just crash.
try {
if (nextIndex >= SIZE)
throw new Exception("Too many readings!");
reading[nextIndex] = new Reading(new Date(), species, count, comment);
nextIndex++;
}
catch (NegativeCountException e) {
System.out.println("Sorry, no negative animals allowed.");
}
}
public String toString(){
String result = "";
for(int i=0; i< nextIndex; i++){
result += reading[i].toString() + "\n";
}
return result;
}
/**
* Write this notebook out to a file. It can be read back using the constructor.
* @param filename name of the file
*
*/
public void writeToFile(String filename) {
try {
ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(filename));
out.writeInt(nextIndex);
out.writeObject(reading);
out.close();
} catch (FileNotFoundException e) {
System.out.println("ERROR: No such file. Did not write.");
} catch (IOException e) {
System.out.println("ERROR: IO. Did not write to file.");
}
}
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
Notebook notebook = new Notebook();
while (true){
System.out.println("Command list: \n");
System.out.println("r - enter new Reading");
System.out.println("l - List all readings");
System.out.println("o - Open file with readings");
System.out.println("w - Write readings to a file");
System.out.println("q - Quit");
System.out.print("\nEnter command:");
String command = keyboard.nextLine();
if (command.equalsIgnoreCase("r")) {
System.out.print("Species name:");
String species = keyboard.nextLine();
System.out.print("Count:");
int count = Integer.parseInt(keyboard.nextLine());
System.out.print("Comment:");
String comment = keyboard.nextLine();
notebook.addReading(species, count, comment);
}
else if (command.equalsIgnoreCase("l")) {
System.out.println(notebook);
}
else if (command.equalsIgnoreCase("o")) {
System.out.print("Enter name of file to read:");
String filename = keyboard.nextLine();
try {
notebook = new Notebook(filename);
}
catch (FileNotFoundException e) {
System.out.println("ERROR: File " + filename + " does not exists.");
}
}
else if (command.equalsIgnoreCase("w")) {
System.out.print("Enter name of file to write to:");
String filename = keyboard.nextLine();
notebook.writeToFile(filename);
}
else if (command.equalsIgnoreCase("q")) {
System.out.println("Bye bye.");
System.exit(0);
}
}
}
}
import java.io.Serializable;
import java.util.Date;
public class Reading implements Serializable {
private Date date;
private String species;
private int count;
private String comment;
public Reading(Date date, String species, int count, String comment) throws NegativeCountException {
super();
if (count < 0)
throw new NegativeCountException("There are no negative animals you dummy.");
this.date = date;
this.species = species;
this.count = count;
this.comment = comment;
}
public String toString() {
return date + "\t" + species + "\t" + count + "\t" + comment;
}
}
public class NegativeCountException extends Exception {
public NegativeCountException(String m) {
super(m);
}
}
Question 8 on page 786.
Hint: refer to binary search class and demo on page 777-778.
add
, max
, and height
. For this homework you will implement these methods.
public class BinarySearchTree {The
private BinarySearchTree left;
private BinarySearchTree right;
private int data;
public BinarySearchTree() {
left = null;
right = null;
}
/** Create a tree that consists of just one node with no children. */
public BinarySearchTree(int data) {
left = null;
right = null;
this.data = data;
}
/** Adds new number n to this BinarySearchTree, placing it in its correct place.
*
* @param n the number to be added
*/
public void add (int n) {
//TODO
}
/** Returns the maximum number in this tree. */
public int max() {
//TODO
}
/** Returns the height of this tree. */
public int height() {
//TODO
}
public String toString() {
return toString("");
}
public String toString(String prefix) {
String result = "";
if (right != null)
result += right.toString(prefix + "-");
else
result += prefix + "- *\n";
result += prefix + " " + data + "\n";
if (left != null)
result += left.toString(prefix + "-");
else
result += prefix + "- *\n";
return result;
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree(8);
tree.add(3);
tree.add(10);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(4);
tree.add(7);
tree.add(13);
System.out.println(tree);
System.out.println("Max=" + tree.max());
System.out.println("Height=" + tree.height());
}
}
main
method shown above constructs the tree shown in the figure. After you properly implement the methods, that main
will run and will print out:
--- * -- 14 ---- * --- 13 ---- * - 10 -- * 8 ---- * --- 7 ---- * -- 6 ---- * --- 4 ---- * - 3 --- * -- 1 --- * Max=14 Height=4This homework is due Tuesday, November 17 at noon.
Question 1 on Page 744.
Note: only use a text file.
CSCE 145: Chapter 11 from Jose Vidal on Vimeo.
CSCE 145: Chapter 10 from Jose Vidal on Vimeo.
You must have watched the screencast by Tuesday, November 3 before class. The textbook slides are below.
Reading
is a specific observation that the user makes. This class has data membersdate
of type Date
, the date of the reading, which you will assign automatically to the current time.species
is a String
which is the name of the species of animal the user saw.count
is an int
that is the number of animals the user saw.comment
a String
comment
Notebook
is a collection of up to 100 readings. It should support, adding a new reading, printing, saving to a file, and reading back from a file.NegativeCountException
is an Exception
that you will raise if the user ever tries to enter a negative number of animals. Your program will throw this exception and also catch it, so the program does not crash.
Your program will support the saving of the whole notebook to a file and the subsequent loading of a notebook from a file. The whole thing will be controlled via a text-based interface, as such:
Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:r Species name:swallowtails Count:3 Comment:Fluttering in the sunshine. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:r Species name:Jezebel Count:11 Comment:Hard to count in the daylight. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine. Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:r Species name:Duke of Burgundy Count:1 Comment:Did not expect to see this one here! Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine. Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight. Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here! Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:w Enter name of file to write to:notebook.dat Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine. Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight. Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here! Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:q Bye bye. //at this point the program stops. //we start it again Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:o Enter name of file to read:notebook.dat Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine. Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight. Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here! Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:r Species name:Speckled wood Count:200 Comment:A gaggle of butterflies. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:l Fri Oct 30 14:11:31 EDT 2009 swallowtails 3 Fluttering in the sunshine. Fri Oct 30 14:12:02 EDT 2009 Jezebel 11 Hard to count in the daylight. Fri Oct 30 14:12:37 EDT 2009 Duke of Burgundy 1 Did not expect to see this one here! Fri Oct 30 14:14:53 EDT 2009 Speckled wood 200 A gaggle of butterflies. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:r Species name:zabulon skipper Count:-1 Comment:lets try this Sorry, no negative animals allowed. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:o Enter name of file to read:thisfilenamedoesnotexist.dat ERROR: File thisfilenamedoesnotexist.dat does not exists. Command list: r - enter new Reading l - List all readings o - Open file with readings w - Write readings to a file q - Quit Enter command:q Bye bye.
This homework is due Tuesday, November 10 @noon.
public class Drink
{
private String name;
private String brand;
private double calories;
public Drink()
{
name = "";
brand = "";
calories = 0;
}
public void setName(String s)
{
name = s;
}
public String getName()
{
return name;
}
public void setBrand(String s)
{
brand = s;
}
public String getBrand()
{
return brand;
}
public void setCal(double i)
{
calories = i;
}
public double getCal()
{
return calories;
}
public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Brand: " + brand);
System.out.println("Calories: " + calories);
}
}
public class FruitJuice extends Drink
{
private double fruitPercentage;
private String fruit;
public FruitJuice()
{
super();
fruitPercentage = 0;
fruit = "";
}
public void setFruitPercentage(double fruit)
{
fruitPercentage = fruit;
}
public double getFruitPercentage()
{
return fruitPercentage;
}
public void setFruit(String s)
{
fruit = s;
}
public String getFruit()
{
return fruit;
}
public void printInfo()
{
super.printInfo();
System.out.println("Fruit Percentage: " + fruitPercentage + "%");
System.out.println("Fruit: " + fruit);
}
}
public class Soda extends Drink
{
private double caffinePercent;
public Soda()
{
super();
caffinePercent = 0;
}
public void setCaffinePercent(double caffine)
{
caffinePercent = caffine;
}
public double getCaffinePercent()
{
return caffinePercent;
}
public void printInfo()
{
super.printInfo();
System.out.println("Caffine Percent: " + caffinePercent + "%");
}
}
import java.util.Scanner;
public class DrinkList
{
public static String lowestCalorie(Drink[] drinks)
{
Drink drink = drinks[0];
for(int i = 0; i < drinks.length; i++)
{
if(drinks[i].getCal() <= drink.getCal())
{
drink = drinks[i];
}
}
String lowest = drink.getName();
return lowest;
}
public static void printAll(Drink[] drinks)
{
for(int i = 0; i < drinks.length; i++)
{
drinks[i].printInfo();
System.out.println();
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
boolean run = true;
System.out.println("How many drinks will you be entering?");
int num = keyboard.nextInt();
System.out.println();
Drink[] drinks = new Drink[num];
for(int i = 1; i <= num; i++)
{
keyboard.nextLine();
System.out.println("Information on Drink " + i + ": ");
System.out.print("Type of Drink (Soda or Fruit) ");
String type = keyboard.nextLine();
System.out.print("Enter " + type + "'s name: ");
String name = keyboard.nextLine();
System.out.print("Enter " + name + "'s brand: ");
String brand = keyboard.nextLine();
System.out.print("Enter " + name + "'s calories: ");
double calories = keyboard.nextDouble();
keyboard.nextLine();
if(type.equalsIgnoreCase("Soda"))
{
System.out.print("Enter the percentage of caffine in " + name + ": ");
double caffine = keyboard.nextDouble();
Soda soda = new Soda();
soda.setName(name);
soda.setBrand(brand);
soda.setCal(calories);
soda.setCaffinePercent(caffine);
drinks[i - 1] = soda;
}
else if(type.equalsIgnoreCase("Fruit"))
{
System.out.print("Enter the fruit in " + name + ": ");
String fruit = keyboard.nextLine();
System.out.print("Enter the percentage vitamin (Daily value) in " + name + ": ");
double vitamin = keyboard.nextDouble();
FruitJuice juice = new FruitJuice();
juice.setName(name);
juice.setBrand(brand);
juice.setCal(calories);
juice.setFruit(fruit);
juice.setFruitPercentage(vitamin);
drinks[i - 1] = juice;
}
else
{
System.out.println("Sorry, but I didn't recognize the kind of drink.");
System.out.println("Next time put the type in right.");
i--;
}
System.out.println();
}
String option = keyboard.nextLine();
do
{
System.out.println("Enter choice (\"Lowest Calorie\", \"PrintAll\", or \"exit\" ): ");
option = keyboard.nextLine();
if(option.equalsIgnoreCase("Lowest Calorie"))
{
System.out.println(lowestCalorie(drinks));
}
else if(option.equalsIgnoreCase("PrintAll"))
{
printAll(drinks);
}
else
{
System.out.println("Please enter one of the available commands.");
}
}while(!option.equalsIgnoreCase("Exit"));
System.out.println("Thanks for using the program. :)");
}
}
CSCE 145: Chapter 9 from Jose Vidal on Vimeo.
public static void main (String[] args){prints out the following when run (every
//create animal with name "bunny" and weight of 10
Animal bunny = new Animal("bunny", 10);
Animal fox = new Animal();
System.out.println(fox);
System.out.println(bunny);
bunny.feed(4);
System.out.println(bunny);
}
println
in the code above corresponds to one line below):
name: weight:-1 name:bunny weight:10 name:bunny weight:14Implement the missing
Animal
class so that it works as shown.public class Animal {
private String name;
private int weight;
public Animal (){
name = "";
weight = -1;
};
public Animal (String n, int w){
name = n;
weight = w;
}
public String toString(){
String result = "name:" + name + " weight:" + weight;
return result;
}
public void feed(int amount){
weight += amount;
}
}
public class Counter {
public static int alpha;
public int beta;
public Counter (){
alpha = 5;
beta = 10;
}
public void increase() {
alpha = alpha + 1;
beta = beta + 1;
}
public String toString() {
return "alpha=" + alpha +" beta=" + beta;
}
public static void main(String[] args){
Counter x = new Counter();
Counter y = new Counter();
System.out.println(x);
System.out.println(y);
x.increase();
System.out.println(x);
System.out.println(y);
Counter z = new Counter();
System.out.println(z);
System.out.println(x);
}
}
alpha=5 beta=10 alpha=5 beta=10 alpha=6 beta=11 alpha=6 beta=10 alpha=5 beta=10 alpha=5 beta=11
public class Rook {prints out:
public static void main(String[] args){
int[][] board = new int[8][8];
for (int i=0; i < 8; i++){
int[] col = {0,0,0,0,0,0,0,0};
board[i] = col;
}
board[1][5] = 1;
//root has a kill if there is a non-zero number anywhere in row 1, or in column 2.
if (rookCanKill(board,1,2))
System.out.println("Root has kill at 1,2");
else
System.out.println("Root cannot kill at 1,2");
//root has a kill if there is a non-zero number anywhere in row 2, or in column 2.
if (rookCanKill(board,2,2))
System.out.println("Root has kill at 2,2");
else
System.out.println("Root cannot kill at 2,2");
}
}
Root has kill at 1,2 Root cannot kill at 2,2Implement the public static boolean rookCanKill(int[][] board, int row, int col) function.
public static boolean rookCanKill(int[][] board, int x, int y){
for (int i=0; i < board.length; i++)
if (board[x][i] != 0) return true;
for (int i=0; i < board.length; i++)
if (board[i][y] != 0) return true;
return false;
}
main
?
public class A {
public A (){
System.out.println("Creating A");
}
public void talk (){
System.out.println("I am A!");
}
public void whine(){
System.out.println("I am Always last.");
}
public void whine(int x){
System.out.println("Am I late?");
}
}
public class B extends A{
public B (){
System.out.println("Creating B");
}
public void talk (){
System.out.println("I am B!");
}
public void whine(){
System.out.println("I am Bored.");
}
}
public class C extends B{
public C (){
System.out.println("Creating C");
}
public void talk (){
System.out.println("I am C!");
}
public void whine(){
System.out.println("I am Cursed.");
super.whine();
}
public void whine(int x){
System.out.println("I am Crazy.");
whine();
}
public static void main(String[] args){
C c = new C();
c.talk();
c.whine();
B b = (B) c;
b.talk();
b = new B();
b.whine();
}
}
Creating A Creating B Creating C I am C! I am Cursed. I am Bored. I am C! Creating A Creating B I am Bored.
Month | Days |
---|---|
January | 31 |
February | 28 |
March | 31 |
April | 30 |
May | 31 |
June | 30 |
July | 31 |
August | 31 |
September | 30 |
October | 31 |
November | 30 |
December | 31 |
dayNumber
which has the number of the day of the month for each day of the year, as such:
dayNumber[0] = 1 dayNumber[1] = 2 : dayNumber[30] = 31 dayNumber[31] = 1 //February first dayNumber[32] = 2 : dayNumber[58] = 28 dayNumber[59] = 1 : : dayNumber[364] = 31You will not receive credit for writing down 365 assignment statements, or for writing an array literal with each of the 365 values in it. You should use a for-loop. Hint: use an array literal to store the number of days in each month.
public class Days{
public static void main(String[] args){
int[] dayNumber = new int[365];
int[] daysInMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
int day = 1;
int month = 0;
int i = 0;
while (month < daysInMonth.length){
dayNumber[i] = day;
i++;
day++;
if (day > daysInMonth[month]){
day = 1;
month++;
}
}
//print it out
for (i=0;i<dayNumber.length;i++)
System.out.println(i + " " + dayNumber[i]);
}
}
The Drink.java class is the super class. It has set and get methods for the attributes name, brand, calories. The Soda and FruitJuice classes inherit the Drink class. The soda class has attributes caffeine percentage. The FruitJuice has attributes vitaminPercentage and fruit. Add a printInfo method in the Drink class and then override that method in the subclasses.
The DrinkList.java will contain your main method, which is where you will declare your array of Drink items, and control execution. In addition, the DrinkList class has 2 methods:
1) printDrinkWithLowestCalories (Drink[] drink) searches the array for the drink with Lowest calories and prints it's name and brand.
2) printAll(Drink[] drink prints the information of all (this includes Soda and FruitJuice information) drinks stored in the array.
here is the sample output:
Please enter the number of drinks to be read: 2
Data For Drink 1:
Type of Drink (Soda/Fruit)? Soda
Enter Soda's name: Sierra Mist
Enter Sierra Mist's brand: Pepsi Co
Enter calories for Sierra Mist: 150
Enter percentage caffeine for Sierra Mist : 0
Data For Drink 2:
Type of Drink (Soda/Fruit)? Fruit
Enter Name: Orange juice
Enter the brand name of Orange Juice: Tropicana
Enter calories of Tropicana: 240
Enter Tropicana's fruit: Orange
Enter Tropicana's percentage vitamin (Daily value): 100
Enter choice ("Low Calorie" or "PrintAll" or "exit" ): Low Calorie
Sierra Mist
Enter choice ("Low Calorie" or "Brand" or "exit" ): exit
Thank you for using the program.
HINT: declare printAll(Drink[] drink) as static method in DrinkList class like this:
public static void/String printAll(Drink[] drink)
NOTE: submit your program before 4:00pm to espiggy@gmail.com. NO late submittion accepted!!
public class Sudoku {
/** 0 means box is blank, otherwise only numbers 1..9 are allowed */
private int[][] board = new int[9][9];
public Sudoku(){
board[0][0] = 1;
// board[0][1] = 1;
}
/** @return true if theBoard[rowoffset..rowoffset+2][coloffset..coloffset+2]
* does not contain more than one copy of 1..9. That is, if the 3x3
* box is a legal subbox
*/
private boolean isLegalBox(int[][] theBoard, int rowOffset, int colOffset){
boolean[] check = new boolean[10];
for (int row = rowOffset; row < rowOffset + 3; row++){
for (int col =colOffset; col < colOffset + 3; col++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}
return true;
}
public boolean isLegalBoard(int [][] theBoard){
//check all rows
for (int row = 0; row < 9; row++){
boolean[] check = new boolean[10];
for (int i =0; i < 10; i++)
check[i] = false;
for (int col =0; col < 9; col++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}
//check all columns
for (int col = 0; col < 9; col++){
boolean[] check = new boolean[10];
for (int i =0; i < 10; i++)
check[i] = false;
for (int row =0; row < 9; row++){
if (board[row][col] == 0)
continue;
if (check[ board[row][col] ])
return false;
else
check[ board[row][col] ] = true;
}
}
//check all 9 boxes
for (int row = 0; row < 9; row+=3){
for (int col =0; col < 9; col+=3){
if (! isLegalBox(theBoard, row, col))
return false;
}
}
return true;
}
public boolean isLegal(){
return isLegalBoard(board);
}
public String toString(){
String result = "";
for (int row = 0; row < 9; row++){
for (int col =0; col < 9; col++){
result += Integer.toString(board[row][col]) + " ";
}
result += "\n";
}
return result;
}
}
Define a Class named Product whose objects are records for a department. A Product has the id number (use type String). Define a Class named Book. Derive this class from Product. You can define the attributes of Book. For example, A Book object has the id (defined in Product class), the book name (use type String) and the price (use type double). Define another Class named Shirt. Derive this class from Product. Define the attributes of Shirt. For example, A Shirt object has the id (defined in Product class), the color (use type String), and the size (use type String). Give your classes a reasonable complement of constructions and accessor methods, and a toString() methods which can display the infomation of product in the cart.
Define a Class named Cart whose objects are records for customer. A customer has the contents which is the array of Product in the cart. Give your classes a reasonable complement of constructions and accessor methods, a add mothods with product object as parameter which can add the product to your cart (the array of product), and a toString() methods which can display the infomation of all product in the cart
// FifteenPuzzle.java
public class FifteenPuzzle {
private int[][] board;
private int blank_x;
private int blank_y;
public FifteenPuzzle()
{
this.board = new int[4][4];
int num = 1;
for (int i=0; i<4; ++i)
for (int j=0; j<4; ++j)
{
this.board[i][j] = num++;
}
this.blank_x = 3;
this.blank_y = 3;
}
public String toString()
{
String strBoard="";
for (int i=0; i<4; ++i)
{
for (int j=0; j<4; ++j)
{
if (this.board[i][j]==16)
strBoard += " ";
else
strBoard += String.format("%3d",this.board[i][j]);
}
strBoard += "\n";
}
return strBoard;
}
public boolean moveUp()
{
if (this.blank_x>0)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x-1][blank_y];
this.board[blank_x-1][blank_y]=temp;
this.blank_x--;
return true;
}
return false;
}
public boolean moveDown()
{
if (this.blank_x<3)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x+1][blank_y];
this.board[blank_x+1][blank_y]=temp;
this.blank_x++;
return true;
}
return false;
}
public boolean moveLeft()
{
if (this.blank_y>0)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x][blank_y-1];
this.board[blank_x][blank_y-1]=temp;
this.blank_y--;
return true;
}
return false;
}
public boolean moveRight()
{
if (this.blank_y<3)
{
int temp = this.board[blank_x][blank_y];
this.board[blank_x][blank_y]=this.board[blank_x][blank_y+1];
this.board[blank_x][blank_y+1]=temp;
this.blank_y++;
return true;
}
return false;
}
public boolean isWinner()
{
int num = 1;
for (int i=0; i<4; ++i)
for (int j=0; j<4; ++j)
{
if (this.board[i][j] != num++)
return false;
}
return true;
}
}
// Demo.java
// report bugs to xusun09@gmail.com
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FifteenPuzzle fp = new FifteenPuzzle();
System.out.println(fp.toString());
System.out.println("Enter command or 'done' to finish");
while(true)
{
System.out.print("Enter command (u,d,l,r):");
String command = reader.nextLine().toLowerCase();
if (command.equals("u"))
fp.moveUp();
else if (command.equals("d"))
fp.moveDown();
else if (command.equals("l"))
fp.moveLeft();
else if (command.equals("r"))
fp.moveRight();
else if (command.equals("done"))
break;
System.out.println(fp.toString());
if (fp.isWinner())
System.out.println("WINNING BOARD!!\n");
}
}
}
toString
that adds all the information particular to that class to the string, and that calls the parent toString
method to get the common parts. For example, only movies have a rating but all media has a title.equals
method in Media
only test that the titles are the same, but the one in Song
also tests that the artists are the same.main
method that tests all your classes and their methods.// Vector.java
public class Vector {
private double dx,dy;
public Vector(double _x, double _y)
{
this.dx = _x;
this.dy = _y;
}
public void addVector(Vector otherVector)
{
this.dx += otherVector.dx;
this.dy += otherVector.dy;
}
public void subtractVector(Vector otherVector)
{
this.dx -= otherVector.dx;
this.dy -= otherVector.dy;
}
public void multiply(int a)
{
this.dx *= a;
this.dy *= a;
}
public double getMagnitude()
{
return Math.sqrt(dx*dx+dy*dy);
}
public void normalize()
{
double magnitude = getMagnitude();
if (magnitude==0)
return;
this.dx /= magnitude;
this.dy /= magnitude;
}
public String toString()
{
return ("("+Double.toString(this.dx)+", "+Double.toString(this.dy)+")");
}
}
//VectorDemo.java
public class VectorDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v1 = new Vector(3,4);
System.out.println(v1.toString());
v1.multiply(3);
System.out.println(v1.toString());
Vector v2 = new Vector(6, 8);
v1.subtractVector(v2);
System.out.println(v1.toString());
v1.normalize();
System.out.println(v1.toString());
}
}
In the fifteen puzzle you are given a board with embedded tiles, numbered 1 to 15, which can only be moved up, down, left, or right to occupy the one blank spot. That is, you can only move a tile that is a neighbor of the blank spot. Another way of looking at it is to say that you can only move the blank spot up, down, left or right, exchanging it with the tile that is already in that position.
For this homework you will implement a FifteenPuzzle class that has the following methods:
toString()
method which prints a pretty board, like the ones shown below.moveUp
, moveDown
, moveLeft
, and moveRight
which move the empty space up, down, left, and right, respectively. The functions should do nothing if called with a board configuration that would make it impossible to execute the action. For example, if the space is in the bottom right and we ask it to moveDown
it should stay there. The program should not crash.isWinner
which returns true if the board is in its initial configuration.You will also implement a main
function that asks the user which way he would like to move the tile and then performs the move, by calling one of the moveX
methods, and displays the new board. Below is a sample interaction with the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Enter command or 'done' to finish Enter command (u,d,l,r):u 1 2 3 4 5 6 7 8 9 10 11 13 14 15 12 Enter command (u,d,l,r):r 1 2 3 4 5 6 7 8 9 10 11 13 14 15 12 Enter command (u,d,l,r):l 1 2 3 4 5 6 7 8 9 10 11 13 14 15 12 Enter command (u,d,l,r):r 1 2 3 4 5 6 7 8 9 10 11 13 14 15 12 Enter command (u,d,l,r):d 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 WINNING BOARD!! Enter command (u,d,l,r):l 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Enter command (u,d,l,r):l 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Enter command (u,d,l,r):u 1 2 3 4 5 6 7 8 9 11 12 13 10 14 15 Enter command (u,d,l,r):u 1 2 3 4 5 7 8 9 6 11 12 13 10 14 15 Enter command (u,d,l,r):r 1 2 3 4 5 7 8 9 6 11 12 13 10 14 15 Enter command (u,d,l,r):d 1 2 3 4 5 7 11 8 9 6 12 13 10 14 15 Enter command (u,d,l,r):done
You must use a 2-dimensional array to implement the board. This homework is due by Thursday, October 15 @ noon.
Tip: To turn an integer into a string that is padded on the left with enough spaces to ensure it is of length at least 3, use String iAsPaddedString = String.format("%3d",i);
where i
is the integer.
For hackers only: write a method that solves the puzzle. A good way to do it is using the A-star algorithm. You will learn all about this and other search algorithms if you take our Artificial Intelligence class (CSCE 580)
Below is the screencast for Chapter 8 which covers inheritance and polymorphism. Both of these are features that every object-oriented programming language implements. They help one minimize the number of methods that your program must define. They are overkill for the small programs we will be writing in this class but are indispensable for managing real-world software which is always much larger. You must have watched this screencast by Tuesday, October 13.
CSCE 145: Chapter 8 from Jose Vidal on Vimeo.
Also, here are the slides from the textbook.
Quesiton 1 on page 529.
Have fun!
NOTE: For section 005 (the 2pm section), today's lab has been moved from B205 to Swearingen 1D29 !!!!
Below is the screencast for Chapter 7, which you must have watched by Tuesday, October 6. This chapter intoduces the topic of arrays which are variables that can hold an array of different values. All programming languages have arrays.
CSCE 145: Chapter 7 from Jose Vidal on Vimeo.
Here are the textbook slides for this chapter.
Question 9 on Page 330.
Have fun!
v1
and v2
with components v1.dx
, v1.dy
and v2.dx
, v2.dy
, we can define various vector operations:v1 + v2 = v3
is implemented as v3.dx = v1.dx + v2.dx
and v3.dy = v1.dy + v2.dy
v1 - v2 = v3
is implemented as v3.dx = v1.dx - v2.dx
and v3.dy = v1.dy - v2.dy
v1 * c = v2
where c
is a constant is implemented as v2.dx = v1.dx * c
and v2.dy = v1.dy * c
v1
is a number equal to the square root of v1.dx*v1.dx + v1.dy*v1.dy
.v1
can be normalized by setting v1.dx = v1.dx / v1.magnitude
and v1.dy = v1.dy / v1.magnitude
Vector
class that has the following data members:public void addVector(Vector otherVector)
which adds otherVector
to this vectorpublic void subtractVector(Vector otherVector)
which subtracts otherVector
from this vectorpublic void multiply(int a)
does a scalar multiplication of this vector by a
public double getMagnitude()
returns the magnitude of this vector. public void normalize()
normalizes this vector.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.
import java.util.Scanner;
public class Labtest1demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
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));
}
}
}
public class BrokenA {
public static final double RATE = 0.5;
public static void main(String[] args) {
double x = 0;
x = 10 * RATE;
RATE = 20;
}
}
RATE
which is a final
variable.
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
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);
}
}
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.
Please enter your name:
YiYi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :
AddEnter the first number:
2Enter the second number:
22The value of 2 + 22 is:
24Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :
multiplyEnter the first number:
3Enter the second number:
5The value of 3 * 5 is:
15Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :
AdddError: Addd is an invalid input
Yi, please enter "Add" for addition, "Minus" for subtraction, "Multiply" for multiplication, or "Exit" to quit :
ExitYi 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!