Unit 1: Primitive Types
1.2.5 Welcome Program | public class Welcome { public static void main(String[] args) { System.out.println(“My name is Eva.”); System.out.println(“I like opals.”); } } |
1.2.6 ASCII Art | public class Art { public static void main(String[] args) { System.out.println(” /)“); System.out.println(“/ O|“); System.out.println(“/ )”); System.out.println(“/ )_/”); } } |
1.2.7 Fixing a Paragraph | public class TomatoEssay { public static void main(String[] args) { // Start here! System.out.println(“Is a tomato a fruit or a vegetable?”); System.out.println(“While biologically speaking a tomato is a fruit, legally speaking it is a vegetable!”); System.out.println(“In Supreme Court Case Nix v. Hedden, the Court ruled that tomatoes should be classified as a vegetable under U.S Customs regulations because they are consumed more like a vegetable than a fruit, and should be taxed as such.”); System.out.println(“When tomatoes are shipped into the U.S, they are now taxed as vegetables even though their anatomy suggests otherwise.”); } } |
1.2.8 Heating Up | public class MakingPopcorn { public static void main(String[] args) { // Start here! System.out.println(“3 Ways to Heat Anything”); System.out.println(“Each of the 3 methods below is an example of the three ways that heat can be transferred.”); System.out.println(); System.out.println(“Conduction”); System.out.println(“Conduction is heat transfer through matter. Metals conduct heat well, but air does not. This is a direct contact type of heat transfer. “); System.out.println(); System.out.println(“Convection”); System.out.println(“Convection is heat transfer by the movement of mass from one place to another. It can take place only in liquids and gases. Heat gained by conduction or radiation is moved by convection. “); System.out.println(); System.out.println(“Radiation”); System.out.println(“Radiation can transfer heat through the relative emptiness of space. All other forms of heat transfer require motion of molecules like air or water to move heat.”); } } |
1.2.9 Personal Timeline | public class Timeline { public static void main(String[] args) { // Modify the code to your life and delete this comment System.out.println(“Age |”); System.out.println(“6 | 06/11 I got my cat Scarlett.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); System.out.println(“8 | 03/13 I can’t think of anything significant.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); System.out.println(“10 | 05/2015 I went to Arizona to visit my grandparents.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); System.out.println(“12 | 02/2017 I went to Chicago with my mom, sister, and grandma.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); System.out.println(“14 | 04/2019 Started to draw more.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); System.out.println(“16 | 03/2021 Made a website.”); System.out.println(” |”); System.out.println(” |”); System.out.println(” |”); } } |
1.3.5 Our First Integer | public class Variables { public static void main(String[] args) { // Modify numYear to current year int numYear = 2022; System.out.print(“The year is”); System.out.print( numYear); } } |
1.3.9 Answering Questions | public class Variables { public static void main(String[] args) { String myName = “Karel the Dog”; int luckyNumber = 11; double currentTemperature = 75.3; boolean isStudent = true; System.out.println(myName); System.out.println(luckyNumber); System.out.println(currentTemperature); System.out.println(isStudent); } } |
1.3.10 Team Rankings | public class TeamRanks { public static void main(String[] args) { String team1 = “Alabama”; String team2 = “Ohio State”; String team3 = “Florida State”; String team4 = “USC”; String team5 = “Clemson”; String team6 = “Penn State”; String team7 = “Oklahoma”; String team8 = “Maryland”; String team9 = “Wisconsin”; String team10 = “Michigan”; /* Don’t edit above this line. Enter your code below this comment. / String temp = team2; team2 = team6; team6 = temp; temp = team3; team3 = team8; team8 = temp; temp = team4; team4 = team10; team10 = temp; temp = team5; team5 = team10; team10 = temp; temp = team6; team6 = team10; team10 = temp; temp = team8; team8 = team9; team9 = temp; / Don’t edit below this line. Enter your code above this comment. */ System.out.print(“1. “); System.out.println(team1); System.out.print(“2. “); System.out.println(team2); System.out.print(“3. “); System.out.println(team3); System.out.print(“4. “); System.out.println(team4); System.out.print(“5. “); System.out.println(team5); System.out.print(“6. “); System.out.println(team6); System.out.print(“7. “); System.out.println(team7); System.out.print(“8. “); System.out.println(team8); System.out.print(“9. “); System.out.println(team9); System.out.print(“10. “); System.out.println(team10); } } |
1.4.6 Weight of a Pyramid | public class Pyramid { public static void main(String[] args) { int numBlocks = 2500000; double blockWeight = 2.5; System.out.print(“The pyramid weighs”); System.out.print( numBlocks * blockWeight); } } |
1,4.7 Add Fractions | public class AddFractions { public static void main(String[] args) { // Define variables int firstNum = 1; int firstDen = 2; int secondNum = 2; int secondDen = 5; int newNum, newDen; // Show the components of the two fractions System.out.print(“The numerator of the first fraction is ” + firstNum); System.out.print(“The denominator of the first fraction is ” + firstDen); System.out.print(“The numerator of the second fraction is ” + secondNum); System.out.print(“The denominator of the second fraction is ” + secondDen); // Do the calculation before printing the answer. newNum = (firstNum * secondDen + secondNum * firstDen); newDen = firstDen * secondDen; System.out.print(firstNum + “/” + firstDen + “+” + secondNum + “/” + secondDen + “=” + newNum + “/” + newDen); } } |
1.4.8 Freely Falling Bodies | public class FallingBodies { public static void main(String[] args) { double time = 10; double timeFall = 100; double g = 9.8; double h = .5gtimeFall; double v = g*time; System.out.println(“The height should be ” + h + ” meters”); System.out.println(“The velocity of the thing should be ” + v); } } |
1.5.5 Work Shift | public class WorkShift { public static void main(String[] args) { int workHoursPreLunch = 10; int workHoursPostLunch = 10; workHoursPostLunch += workHoursPreLunch; int fullHourMinute = 60; int minutes = 42; int seconds = 16; workHoursPostLunch *= fullHourMinute; workHoursPostLunch *= fullHourMinute; seconds += workHoursPostLunch; minutes *= fullHourMinute; seconds += minutes; int secondsTotal = seconds; System.out.print (“The doctor worked ” + secondsTotal + ” seconds”); } } |
1.5.6 My Age | public class MyAge { public static void main(String[] args) { int age = 17; System.out.println(“My current age is:” + 17); age++; System.out.println(“My age next year will be:” + age); age–; System.out.println(“My current age is:” + age); } } |
1.6.5 My Age (User Input) | import java.util.Scanner; //Refer to your code from the previous My Age exercise. // Modify it using the Scanner class to take user input instead of hard coding in your age. public class MyAge { public static void main(String[] args) { int age; Scanner input = new Scanner(System.in); System.out.println(“Please enter your current age:”); age = input.nextInt(); System.out.println(“My current age is:” + age); age++; System.out.println(“My age next year will be:” + age); age–; System.out.println(“My current age is:” + age); } } |
1.6.6 Night Out | import java.util.*; public class NightOut { public static void main(String[] args) { double numDinner; double numGolf; double numDessert; Scanner input = new Scanner(System.in); System.out.println(“How much did dinner cost?”); numDinner = input.nextDouble(); System.out.println(“How much is mini-golf for one person?”); numGolf = input.nextDouble(); System.out.println(“How much did dessert cost?”); numDessert = input.nextDouble(); System.out.println(“Dinner: $” + numDinner); System.out.println(“Mini-Golf: $” + numGolf); System.out.println(“Dessert: $” + numDessert); double numTotal = numDinner + (numGolf * 2) + numDessert; System.out.println(“Grand Total: $” + numTotal); } } |
1.6.7 MLA CItation | import java.util.Scanner; public class Citation { public static void main(String[] args) { Scanner input = new Scanner(System.in); String stringName; int numYear; String stringTitle; String stringPublisher; System.out.println(“Enter the author’s name as ‘Last name, First name’: “); stringName = input.nextLine(); System.out.println(“Enter the title of the book:”); stringTitle = input.nextLine(); System.out.println(“Enter the publisher of the book:”); stringPublisher = input.nextLine(); System.out.println(“Enter the year the book was published:”); numYear = input.nextInt(); System.out.println(stringName + “. ” + stringTitle + “.”); System.out.println(stringPublisher + “, ” + numYear + “.”); } } |
1.7.4 Casting to an Int | import java.util.Scanner; public class CastingToInt { public static void main(String[] args) { double myDouble; Scanner input = new Scanner(System.in); System.out.println(“Enter a double with a decimal value:”); myDouble = input.nextDouble(); int castingNum = (int)myDouble; System.out.println(castingNum); } } |
1.7.5 Casting to a Double | import java.util.Scanner; public class CastingToDouble { public static void main(String[] args) { Scanner input = new Scanner(System.in); int int1; int int2; System.out.println(“First Int:”); int1 = input.nextInt(); System.out.println(“Second Int:”); int2 = input.nextInt(); double intDivide = (double)int1 / (double)int2; System.out.println(intDivide); } } |
1.7.8 Movie Ratings | import java.util.Scanner; public class MovieRatings { public static void main(String[] args) { Scanner input = new Scanner(System.in); double movieRating; System.out.println(“Enter movie rating (as a decimal):”); movieRating = input.nextDouble(); int ratingRound = (int) (movieRating + 0.5); System.out.println(ratingRound); } } |
1.7.11 Integer Overflow | public class IntegerOverflow { public static void main(String[] args) { System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MIN_VALUE + 1); System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MAX_VALUE + 1); } } |
Unit 2: Using Objects
2.1.8 Pizza | public class Pizza { // Add your instance variables here boolean pizzaglutenfree; String pizzatopping1; String pizzatopping2; String pizzatopping3; int pizzadiameter; public Pizza(boolean glutenfree, String topping1, String topping2, String topping3, int diameter){ pizzaglutenfree = glutenfree; pizzatopping1 = topping1; pizzatopping2 = topping2; pizzatopping3 = topping3; pizzadiameter = diameter; } } |
2.1.8 Pizza Tester | public class PizzaTester { public static void main(String[] args) { System.out.println(“You should be able to run this”); System.out.println(“if you added the instance variables correctly”); Pizza myPizza = new Pizza(true, “pepperoni”, “mushrooms”, “tomatoes”, 16); } } |
2.1.9 Phone | @@ -0,0 +1,26 @@ /** The phone class represents a cellular phone. Add the instance variables you think a phone would need */ public class Phone { // Attributes boolean phoneTouchscreen; String phoneContact1; String phoneContact2; String phoneContact3; int phoneNumber; public Phone(boolean touchscreen, String contact1, String contact2, String contact3, int number){ phoneTouchscreen = touchscreen; phoneContact1 = contact1; phoneContact2 = contact2; phoneContact3 = contact3; phoneNumber = number; } } |
2.2.6 Rectangle | public class Rectangle { // Attributes private int width; private int height; // Constructor public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; } // This method lets us print out the object // to see the values of the instance variables public String toString() { return “Rectangle with width: ” + width + ” and height: ” + height; } } |
Rectangle Tester | public class RectangleTester { public static void main(String[] args) { // Create a rectangle with width 5 and height 12 // Then print it out Rectangle myRectangle = new Rectangle(5, 12); System.out.println(myRectangle); } } |
2.2.7 Student | @@ -0,0 +1,36 @@ public class Student { private String firstName; private String lastName; private int gradeLevel; // Add GPA instance variable called gpa here. private double gpa; /** * This is a constructor. A constructor is a method * that creates an object — it creates an instance * of the class. What that means is it takes the input * parameters and sets the instance variables (or fields) * to the proper values. * * Check out StudentTester.java for an example of how to use * this constructor and how to add the gpa to the constructor. */ public Student(String fName, String lName, int grade, double gradepointaverage) { firstName = fName; lastName = lName; gradeLevel = grade; gpa = gradepointaverage; } /** * This is a toString for the Student class. It returns a String * representation of the object, which includes the fields * in that object. */ public String toString() { return firstName + ” ” + lastName + ” is in grade: ” + gradeLevel + ” and has GPA: ” + gpa; } } |
2.3.7 Coffee | @@ -0,0 +1,41 @@ /* This class represents a cup of coffee */ public class Coffee { // Instance Variables private int brewStrength; // on a scale of 1 to 5, 5 being the darkest private boolean sugar; // has sugar (true) or does not (false) // takes the values “none”, “whole”, “nonfat”, “soy”, or “almond” private String milkType; // Add a default constructor (no parameters) // to initialize the instance variables // to a default cup of coffee public Coffee() { brewStrength = 3; sugar = true; milkType = “whole”; } // Specialized constructor public Coffee(int howStrong, boolean hasSugar, String milk) { brewStrength = howStrong; sugar = hasSugar; milkType = milk; } // String representation to print // Do not modify this function public String toString() { return “Coffee brewed to level ” + brewStrength + ” with ” + milkType + ” milk. Sugar? ” + sugar; } } |
2.3.8 Pinata | @@ -0,0 +1,46 @@ public class Pinata { // Instance variables private String candy; // what kind of candy is inside private String color; private String shape; // Constructor without parameters public Pinata() { candy = “hard candy”; color = “rainbow”; shape = “donkey”; } // Add an overloaded constructor that allows the user // to customize all of the instance variables public Pinata(String theCandy, String theColor, String theShape) { candy = theCandy; color = theColor; shape = theShape; } // Add an overloaded constructor that allows the user // to customize the color and shape public Pinata(String theColor, String theShape) { candy = “hard candy”; color = theColor; shape = theShape; } // Add an overloaded constructor that allows the user // to customize the candy public Pinata(String theCandy) { candy = theCandy; color = “rainbow”; shape = “donkey”; } public String toString() { return color + ” ” + shape + ” pinata filled with ” + candy; } } |
2.2.8 Dog | @@ -0,0 +1,20 @@ public class Dog { private String breed; // Add an instance variable here for name. private String name; public Dog(String theBreed, String theName) { breed = theBreed; name = theName; } // This method should work after you add the // new instance variable and update the constructor. // DO NOT modify this method. public String toString() { return name + ” is a ” + breed; } } |
2.2.9 Pizza | @@ -0,0 +1,24 @@ public class Pizza { // Add the instance variables here private String type; private String toppings; private int size; // Put the constructor here public Pizza(String theType, String theToppings, int theSize){ type = theType; toppings = theToppings; size = theSize; } // You don’t need to do anything with this method // Used to print the object public String toString() { return size + ” inch ” + type + ” pizza with ” + toppings; } } |
2.3.9 Website | @@ -0,0 +1,39 @@ public class Website { // Put your code here private String domain; private String topLevelDomain; private int numUsers; public Website() { domain = “”; topLevelDomain = “com”; numUsers = 0; } public Website(String theDomainName, String theTopDomain) { domain = theDomainName; topLevelDomain = theTopDomain; numUsers = 0; } public Website(String theDomainName, String theTopDomain, int theNumPeople) { domain = theDomainName; topLevelDomain = theTopDomain; numUsers = theNumPeople; } // String representation for printing // Do not modify this method public String toString() { String res = “https://www.” + domain + “.” + topLevelDomain; res += ” has ” + numUsers + ” users”; return res; } } |
2.3.10 Rectangle | @@ -0,0 +1,33 @@ public class Rectangle { // Attributes private int width; private int height; // Constructor // Copies the values of rectWidth and rectHeight // into width and height, respectively public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; } // Constructor // Allows user to construct a square // Copies the value of sidelength // into both width and height public Rectangle(int sidelength) { width = sidelength; height = sidelength; } // This method lets us print out the object // to see the values of the instance variables public String toString() { return “Rectangle with width: ” + width + ” and height: ” + height; } } |
2.4.5 Hello | @@ -0,0 +1,45 @@ public class Hello { private String name; public Hello (String yourName){ name = yourName; } public void english(){ System.out.print(“Hello “); System.out.print(name); System.out.println(“!”); } public void spanish(){ System.out.print(“Hola “); System.out.print(name); System.out.println(“!”); } public void french(){ System.out.print(“Bonjour “); System.out.print(name); System.out.println(“!”); } public void german(){ System.out.print(“Hallo “); System.out.print(name); System.out.println(“!”); } public void russian(){ System.out.print(“Privet “); System.out.print(name); System.out.println(“!”); } public void chinese(){ System.out.print(“Ni hao “); System.out.print(name); System.out.println(“!”); } } |
2.4.6 Coins | @@ -0,0 +1,77 @@ public class Coins { private int quarters; private int dimes; private int nickels; private int pennies; public Coins(int numQuarters, int numDimes, int numNickels, int numPennies){ quarters = numQuarters; dimes = numDimes; nickels = numNickels; pennies = numPennies; } public void addQuarter(){ System.out.println(“Adding a quarter …”); quarters ++; } public void addDime(){ System.out.println(“Adding a dime …”); dimes ++; } public void addNickel(){ System.out.println(“Adding a nickel …”); nickels ++; } public void addPenny(){ System.out.println(“Adding a penny …”); pennies ++; } public void quartersCount(){ System.out.println(quarters); } public void quartersTotal(){ System.out.println(quarters * 0.25); } public void dimesCount(){ System.out.println(dimes); } public void dimesTotal(){ System.out.println(dimes * 0.10); } public void nickelsCount(){ System.out.println(nickels); } public void nickelsTotal(){ System.out.println(nickels * 0.05); } public void penniesCount(){ System.out.println(pennies); } public void penniesTotal(){ System.out.println(pennies * 0.01); } public void bankValue(){ System.out.println(quarters * 0.25 + dimes * 0.10 + nickels * 0.05 + pennies * 0.01); } public void bankCount(){ System.out.println(quarters + dimes + nickels + pennies); } } |
2.4.7 Bot | public class Bot { private String name; public Bot (String yourName){ name = yourName; } public void greeting(){ System.out.print(“Hello “); System.out.print(name); System.out.println(“! My name is Hal!”); System.out.println(“How are you today!”); } public void help(){ System.out.println(“You can ask me about the weather,”); System.out.println(“or how many feet are in a mile.”); System.out.println(“I can even convert feet to meters!”); } public void weather(){ System.out.println(“Its always warm and dry inside your computer!”); } public void feetInMile() { System.out.println(“There are 5280 feet in a mile.”); } public void goodbye(){ System.out.println(“It was nice talking with you!”); System.out.println(“Have a great day!”); } public void favoriteNumber(int yourNumber){ System.out.println(“My favorite number is 8.”); System.out.print(“That is “); System.out.print(yourNumber – 8); System.out.println(” away from your number”); } public double feetToMeters(double feet){ double meters = feet * 0.3048; return meters; } } |
2.4.8 Salutations | @@ -0,0 +1,32 @@ public class Salutations { // Put your code here private String name; public Salutations(String myName) { name = myName; } public void addressLetter() { System.out.println("Dear " + name); } public void signLetter() { System.out.println("Sincerely,"); System.out.println(name); } public void addressMemo() { System.out.println("To whom it may concern"); } public void signMemo() { System.out.println("Best,"); System.out.println(name); } } |
2.5.5 Point | @@ -0,0 +1,22 @@ public class Point { private int x; private int y; public Point(int xCoord, int yCoord) { x = xCoord; y = yCoord; } public void move(int dx, int dy) { x += dx; y += dy; } public String toString() { return x + “, ” + y; } } |
2.5.7 Basket ball Player.java | @@ -0,0 +1,47 @@ public class BasketballPlayer { /* This class is complete. Take a look around * to make sure you understand how to use it, * but you do not need to make changes. */ private String name; private String team; private int totalPoints; private int totalAssists; private int gamesPlayed; public BasketballPlayer(String playerName, String currentTeam) { name = playerName; team = currentTeam; totalPoints = 0; gamesPlayed = 0; } public BasketballPlayer(String playerName) { // this() is a shortcut to calling the other constructor // in this class. We will see more of ‘this’ in a later // unit, but it is shown here as a best practice. this(playerName, “no team”); } public void addGame(int points, int assists) { totalPoints += points; totalAssists += assists; gamesPlayed ++; } public void printPPG() { System.out.print(“Points per game: “); System.out.println((double) totalPoints / gamesPlayed); } public void printAPG() { System.out.print(“Assists per game: “); System.out.println((double) totalAssists / gamesPlayed); } public String toString() { return name + ” averages ” + ((double) totalPoints / gamesPlayed) + ” points per game.”; } } |
2.5.8 Calculator | @@ -0,0 +1,52 @@ public class Calculator { // This class does not need instance variables! // Prints the sum of x and y public void sum(double x, double y) { double result = x + y; System.out.print(x); System.out.print(” + “); System.out.print(y); System.out.print(” = “); System.out.println(result); } // Prints the product of x and y public void multiply(double x, double y) { double result = x * y; System.out.print(x); System.out.print(” * “); System.out.print(y); System.out.print(” = “); System.out.println(result); } // Prints the product of x and y public void divide(double x, double y) { double result = x / y; System.out.print(x); System.out.print(” / “); System.out.print(y); System.out.print(” = “); System.out.println(result); } // Prints the product of x and y public void subtract(double x, double y) { double result = x – y; System.out.print(x); System.out.print(” – “); System.out.print(y); System.out.print(” = “); System.out.println(result); } } |
2.5.9 Bot 2 | @@ -0,0 +1,61 @@ public class Bot2 { private String name; public Bot2 (String yourName){ name = yourName; } public void greeting(){ System.out.print(“Hello “); System.out.print(name); System.out.println(“! My name is Hal!”); System.out.println(“How are you today!”); } public void help(){ System.out.println(“You can ask me about the weather,”); System.out.println(“or how many feet are in a mile.”); System.out.println(“I can even convert feet to meters!”); } public void weather(){ System.out.println(“It’s always warm and dry inside your computer!”); } public void feetInMile() { System.out.println(“There are 5280 feet in a mile.”); } public void goodbye(){ System.out.println(“It was nice talking with you!”); System.out.println(“Have a great day!”); } public void favoriteNumber(int yourNumber){ System.out.println(“My favorite number is 8.”); System.out.print(“That is “); System.out.print(yourNumber – 8); System.out.println(” away from your number.”); } public void favoriteAnimal(String yourAnimal){ System.out.print(“Cool. I also like “); System.out.print(yourAnimal); System.out.println(“s.”); System.out.println(“My favorite animals are dogs. Have you met Karel?”); } public void home(String location){ System.out.print(“I heard it is really nice in “); System.out.print(location); System.out.println(“.”); System.out.println(“I live in a cloud, which is actually pretty cool!”); } public double feetToMeters(double feet){ double meters = feet * 0.3048; return meters; } } |
2.6.6 Number Games | @@ -0,0 +1,36 @@ public class NumberGames { // Keep track of the number private double num; // Constructor public NumberGames(double startingNumber) { num = startingNumber; } // Returns the number public double getNumber() { return num; } // Doubles the number // Returns the doubled number public double doubleNumber() { num *= 2; return num; } // Squares the number // Returns the squared number public double squareNumber() { num *= num; return num; } } |
2.6.7 Construction | @@ -0,0 +1,36 @@ public class Construction { private double lumber; // price per board private double windows; // price per square inch of window private double taxRate; public Construction(double lumberCost, double windowCost, double taxes) { lumber = lumberCost; windows = windowCost; taxRate = taxes; } // Computes and returns the cost // of the lumber public double lumberCost(int numBoards) { return lumber * numBoards; } // Computes and returns the cost of the windows public double windowCost(int numWindows) { return windows * numWindows; } // Computes the grand total by adding // the tax amount to the total public double grandTotal(double total) { return total * (1 + taxRate); } } |
2.6.8 Geo Location | @@ -0,0 +1,64 @@ /* This class stores information about a location on Earth. Locations are specified using latitude and longitude. The class includes a method for computing the distance between two locations. * This implementation is based off of the example from Stuart Reges at the University of Washington. */ public class GeoLocation { // Earth radius in miles public static final double RADIUS = 3963.1676; private double latitude; private double longitude; /** * Constructs a geo location object with given latitude and longitude */ public GeoLocation(double theLatitude, double theLongitude) { latitude = theLatitude; longitude = theLongitude; } /** * Returns the latitude of this geo location */ public double getLatitude() { return latitude; } /** * returns the longitude of this geo location */ public double getLongitude() { return longitude; } // returns a string representation of this geo location public String toString() { return “latitude: ” + latitude + “, longitude: ” + longitude; } // returns the distance in miles between this geo location and the given // other geo location public double distanceFrom(GeoLocation other) { double lat1 = Math.toRadians(latitude); double long1 = Math.toRadians(longitude); double lat2 = Math.toRadians(other.latitude); double long2 = Math.toRadians(other.longitude); // apply the spherical law of cosines with a triangle composed of the // two locations and the north pole double theCos = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(long1 – long2); double arcLength = Math.acos(theCos); return arcLength * RADIUS; } } |
2.7.7 Calculator | @@ -0,0 +1,35 @@ public class Calculator { // This class does not need instance variables! // Since there are no instance variables, // this class also does not need a constructor. // Java will create an empty constructor for you. // Returns the sum of x and y public double sum(double x, double y) { return x + y; } // Returns the product of x and y public double multiply(double x, double y) { return x * y; } // Returns the quotient x / y public double divide(double x, double y) { return x / y; } // Returns the difference of x – y public double subtract(double x, double y) { return x – y; } } |
2.7.8 Form Fill Tester | @@ -0,0 +1,14 @@ public class FormFillTester { public static void main(String[] args) { FormFill filler = new FormFill(“Karel”, “Dog”); filler.setAddress(123, “Cherry Lane”, “4B”); System.out.println(filler.fullName()); System.out.println(filler.streetAddress()); System.out.println(filler.creditCardInfo(123456789, 10, 2025)); } } |
2.7.9 Quote Machine | @@ -0,0 +1,23 @@ import java.util.Scanner; public class QuoteMachine { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Ask for a quote // Ask for the author System.out.println("Enter a quote:"); String quote = input.nextLine(); System.out.println("Enter the author of the quote:"); String author = input.nextLine(); // Create a new String that has the quote in quotation marks // Don't forget to escape the quotation marks String finalQuote = "\"" + quote + "\""; // Print the quote, then the author on the next line // But you can only use ONE print statement! System.out.println(finalQuote + "\n" + author); } } |
2.8.6 Talker | @@ -0,0 +1,46 @@ public class Talker { private String text; // Constructor public Talker(String startingText) { text = startingText; } // Returns the text in all uppercase letters // Find a method in the JavaDocs that // will allow you to do this with just // one method call public String yell() { return text.toUpperCase(); } // Returns the text in all lowercase letters // Find a method in the JavaDocs that // will allow you to do this with just // one method call public String whisper() { return text.toLowerCase(); } // Reset the instance variable to the new text public void setText(String newText) { text = newText; } // Returns a String representatin of this object // The returned String should look like // // I say, "text" // // The quotes should appear in the String // text should be the value of the instance variable public String toString() { return "I say, " + "\"" + text + "\""; } } |
2.8.7 Flower | @@ -0,0 +1,21 @@ public class Flower { private String name; private String color; private String genus; private String species; public Flower(String theName, String theColor, String theGenus, String theSpecies) { name = theName; color = theColor; genus = theGenus; species = theSpecies; } public String toString() { return color + " " + name + " (" + genus + " " + species + ")"; } } |
2.8.8 Filer | @@ -0,0 +1,45 @@ public class Filer { private String word; public Filer(String theWord) { word = theWord; } // Returns the word public String getWord() { return word; } // Returns true if word comes // before otherWord. // Returns false otherwise. public boolean comesBefore(String otherWord) { boolean result = word.compareTo(otherWord) < 0; return result; } // Returns true if word comes // after otherWord. // Returns false otherwise. public boolean comesAfter(String otherWord) { boolean result = word.compareTo(otherWord) > 0; return result; } // Returns true if word is equal to otherWord. // Returns false otherwise. public boolean isEqual(String otherWord) { boolean result = word.equals(otherWord); return result; } } |
2.8.9 Fraction | @@ -0,0 +1,34 @@ public class Fraction { private int numerator; private int denominator; public Fraction(int numer, int denom) { numerator = numer; denominator = denom; } // Returns the numerator public int getNumerator() { return numerator; } // Returns the denominator public int getDenominator() { return denominator; } // Returns a string representing a fraction // in the form // numerator/denominator public String toString() { return numerator + "/" + denominator; } } |
2.8.10 WordGames | @@ -0,0 +1,51 @@ public class WordGames { private String word; public WordGames(String text) { word = text; } public String scramble() { // switch first half // and second half int middle = word.length() / 2; String result = word.substring(middle) + word.substring(0, middle); return result; } public String bananaSplit(int insertIdx, String insertText) { // Insert insertText at the position // insertIdx String firstPart = word.substring(0, insertIdx); String secPart = word.substring(insertIdx); String result = firstPart + insertText + secPart; return result; } public String bananaSplit(String insertChar, String insertText) { // Insert insertText after the first // occurence of the insertChar int insertIDx2 = word.indexOf(insertChar); String firstPart = word.substring(0, insertIDx2); String secPart = word.substring(insertIDx2); String result = firstPart + insertText + secPart; return result; } public String toString() { // Games[word] return "[" + word + "]"; } } |
2.9.6 PickupWindow | @@ -0,0 +1,33 @@ import java.util.Scanner; public class PickupWindow { public static void main(String[] args) { // Create scanner object Scanner input = new Scanner(System.in); // Display menu String menu = "1. Hamburger\n2. Cheeseburger\n3. Veggie Burger\n4. Nachos\n5. Hot Dog\n"; System.out.println(menu); // Get customer order System.out.println("Enter label: "); String customerOrder = input.nextLine(); // Use substring to get the first character (the number) String combo = customerOrder.substring(0, 1); // Create an Integer object by using the static // method Integer.valueOf(someString) // to turn the string into an Integer Integer comboNumber = Integer.valueOf(combo); // Print out what the customer ordered System.out.println("Customer ordered number " + comboNumber); } } |
2.9.7 Currency | @@ -0,0 +1,41 @@ public class Currency { private Double value; // Constructor public Currency(Double startValue) { value = startValue; } // Sets value to newValue public void setValue(Double newValue) { value = newValue; } // Returns the dollar portion of value // if value is 12.34, returns 12 public Integer getDollars() { int dollars = (int) value.doubleValue(); return dollars; } // Returns the cents portion of value // as an Integer // if value is 12.34, returns 34 public Integer getCents() { int cents = (int)(value * 100) % 100; return cents; } // Returns a String representation // in the format // $12.34 public String toString() { return "$" + getDollars() + "." + getCents(); } } |
2.9.8 Extremes | @@ -0,0 +1,35 @@ public class Extremes { Integer min; Integer max; // Constructor public Extremes() { //Set min and max values min = Integer.MIN_VALUE; max = Integer.MAX_VALUE; } // Returns the difference // max - number public Integer maxDiff(Integer number) { return max - number; } // Returns the difference // min - number public Integer minDiff(Integer number) { return min - number; } // Returns a String representation // in the form // [min, max] public String toString() { return "[" + min + ", " + max + "]"; } } |
2.10.6 Circle | public class Circle { private double radius; public Circle(double theRadius) { radius = theRadius; } // Implement getArea using // Math.PI and // Math.pow // Area = pi * r^2 public double getArea() { double area = Math.PI * Math.pow(radius, 2); return area; } // Implement getCircumference using // Math.PI // Circumference = 2 * PI * r public double getCircumference() { double circ = 2 * Math.PI * radius; return circ; } } |
Circle Tester | public class CircleTester { public static void main(String[] args) { Circle cup = new Circle(5); System.out.println(“Area of a circle with radius 5: ” + cup.getArea()); System.out.println(“Circumference of a circle with radius 5: ” + cup.getCircumference()); Circle hat = new Circle(12); System.out.println(“\nArea of a circle with radius 12: ” + hat.getArea()); System.out.println(“Circumference of a circle with radius 12: ” + hat.getCircumference()); } } |
2.10.7 Unit Circle | public class UnitCircle { public static void main(String[] args) { System.out.println(“Radians: (cos, sin)”); // Put your code here! double angle1 = 0.0; double angle2 = Math.PI / 2; double angle3 = Math.PI; double cos1 = Math.round(Math.cos(angle1) * 100) / 100.0; double cos2 = Math.round(Math.cos(angle2) * 100) / 100.0; double cos3 = Math.round(Math.cos(angle3) * 100) / 100.0; double sin1 = Math.round(Math.sin(angle1) * 100) / 100.0; double sin2 = Math.round(Math.sin(angle2) * 100) / 100.0; double sin3 = Math.round(Math.sin(angle3) * 100) / 100.0; System.out.println(angle1 + “: ” + cos1 + “, ” + sin1); System.out.println(angle2 + “: ” + cos2 + “, ” + sin2); System.out.println(angle3 + “: ” + cos3 + “, ” + sin3); } } |
2.10.8 Race Main | public class RaceMain { public static void main(String[] args) { // Length of the course in meters double distance = 2414; // ~ 1.5 miles // Generate a random acceleration for each car double accel1 = Math.random() + 1; double accel2 = Math.random() + 1; // Create two Racecar objects Racecar car1 = new Racecar(accel1, “Hello”); Racecar car2 = new Racecar(accel2, “World”); // Compute the finishing times for both cars double time1 = car1.computeTime(distance); double time2 = car2.computeTime(distance); // Print times of each car System.out.println(“First car finished in ” + time1 + ” seconds”); System.out.println(“Second car finished in ” + time2 + ” seconds”); } } |
Race car | public class Racecar { private double accel; // acceleration private String name; // name of driver public Racecar(double acceleration, String driver) { accel = acceleration; name = driver; } // Returns the time it takes the racecar // to complete the track public double computeTime(double distance) { double t = Math.round((Math.sqrt((2 * distance) / accel)) * 100) / 100.0; return t; } public String toString() { return “Racer ” + name; } } |
Unit 3: Boolean Expressions And If Statements
3.1.6 Relative Numbers | @@ -0,0 +1,22 @@ import java.util.Scanner; public class RelativeNumbers { public static void main(String[] args) { // Ask for two numbers Scanner input = new Scanner(System.in); System.out.println(“Enter two numbers: “); int num1 = input.nextInt(); int num2 = input.nextInt(); // Compare the numbers as instructed boolean bool1 = num1 < num2; boolean bool2 = num1 == num2; boolean bool3 = num1 > num2; // Display the results System.out.println(num1 + " < " + num2 + ": " + bool1); System.out.println(num1 + " == " + num2 + ": " + bool2); System.out.println(num1 + " > " + num2 + ": " + bool3); } } |
3.1.7 Added Sugar | @@ -0,0 +1,16 @@ import java.util.Scanner; public class AddedSugar { public static void main(String[] args) { // Create a Scanner object Scanner input = new Scanner(System.in); // Ask the user for the grams of sugar System.out.println(“How many grams of sugar have you eaten today?”); int grams = input.nextInt(); // Use a boolean expression to print if they can eat more sugar boolean more = grams < 30; System.out.println(“You can eat more sugar: ” + more); } } |
3.1.8 Triple Double | @@ -0,0 +1,27 @@ import java.util.Scanner; public class TripleDouble { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Ask for the three stats System.out.println("How many points did you score?"); int points = input.nextInt(); System.out.println("How many rebounds did you get?"); int rebounds = input.nextInt(); System.out.println("How many assists did you have?"); int assists = input.nextInt(); // Create three boolean variables that // check if the stats are 10 or more boolean bool1 = points >= 10; boolean bool2 = rebounds >= 10; boolean bool3 = assists >= 10; // Print out the value of each boolean // variable. Be sure to label them! System.out.println("You got 10 or more points: " + bool1); System.out.println("You got 10 or more rebounds: " + bool2); System.out.println("You got 10 or more assists: " + bool3); } } |
3.2.6 Discounts | @@ -0,0 +1,22 @@ import java.util.Scanner; public class Discounts { public static void main(String[] args) { // Create a scanner object Scanner input = new Scanner(System.in); // Ask how many hours were you parked System.out.println(“How many hours have you been parked?”); int hours = input.nextInt(); // Compute cost – $3.50 per hour double cost = hours * 3.5; // If cost is over $20, set cost to $20 if(cost > 20) { cost = 20; } // Display the final cost System.out.println(“You owe $” + cost); } } |
3.2.7 Drink Order | @@ -0,0 +1,28 @@ import java.util.Scanner; public class DrinkOrder { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Start here! // You'll find it helpful to list the steps you // need to take, then write the code System.out.println("What do you want to drink?"); String answer = input.nextLine(); System.out.println("How many teaspoons of sugar do you want?"); int sugar = input.nextInt(); System.out.println("Confirming your order. You wanted:"); if(sugar == 0) { System.out.println(answer); } else { System.out.println(answer + " with sugar"); } } } |
3.2.8 Microwave Cooking | @@ -0,0 +1,21 @@ public class MicrowaveCooking { public static void main(String[] args) { // Generate a random number of seconds // between 0 and 60 int rand = (int)(Math.random() * 60); // Print the number of seconds System.out.println(“Microwaving for ” + rand + ” seconds”); // Use two if statements to print // whether the roll is fine or will catch fire if(rand > 20) { System.out.println(“Your roll will catch fire!”); } else { System.out.println(“Perfect cooking time!”); } } } |
3.2.9 Rater | @@ -0,0 +1,49 @@ public class Rater { private String name; // name of company private double rating; // number rating (1 – 5) public Rater(String company, double initialRating) { name = company; rating = initialRating; } // Set rating to newRating // As long as it's no more than 5 public void setRating(double newRating) { if(newRating <= 5) { rating = newRating; } } // Returns the rating of the company public double getRating() { return rating; } // Returns a string representation of the company // based on their ratings public String toString() { // remember, once a return statement is // executed, the program LEAVES the method. // Nothing after the executed return statement is executed. if(rating < 2) { return "Not Recommended Company " + name; } else if(rating > 3.5) { return "Gold Star Company " + name; } else { return "Well Rated Company " + name; } } } |
3.3.5 Numbers | @@ -0,0 +1,19 @@ import java.util.Scanner; public class Numbers { public static void main(String[] args) { // Start here! Scanner input = new Scanner(System.in); int num = input.nextInt(); if(num >= 0) { System.out.println(“The number is positive!”); } else { System.out.println(“The numver is negative!”); } } } |
3.3.6 Battleship | @@ -0,0 +1,44 @@ public class Battleship { private String shipType; private int position; public Battleship(String type, int shipPosition) { shipType = type; position = shipPosition; } // Moves the ship // If safeToMove is true, add 5 to position // else subtract 5 from position public void move (boolean safeToMove) { // Because safeToMove is already a boolean // value, you DO NOT need to compare it to // true // Just use // if(safeToMove) if(safeToMove) { position += 5; } else { position -= 5; } } // Returns the position of the ship public int getPosition() { return position; } // String representation of the object public String toString() { return shipType + " at " + position; } } |
3.3.7 Rater | @@ -0,0 +1,53 @@ public class Rater { private String name; // name of company private double rating; // number rating (1 – 5) private String review; // review shown with company name public Rater(String company, double initialRating) { name = company; rating = initialRating; review = ""; } // Set rating to newRating // As long as it's no more than 5 public void setRating(double newRating) { if(newRating <= 5.0) { rating = newRating; } } // Updates review line based on rating public void updateReview() { if(rating >= 3) { review = "Proudly recommended"; } else { review = "Needs more ratings"; } } // Returns the rating of the company public double getRating() { return rating; } // Returns a string representation of the company // Uses the form // name : review public String toString() { return name + " : " + review; } } |
3.3.8 Basketball | @@ -0,0 +1,41 @@ import java.util.Scanner; public class Basketball { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Start by listing the steps you need to take System.out.println("Enter player one's name:"); String name1 = input.nextLine(); System.out.println("Enter player two's name:"); String name2 = input.nextLine(); System.out.println("Enter " + name1 + "'s score"); int score1 = input.nextInt(); System.out.println("Enter " + name2 + "'s score"); int score2 = input.nextInt(); if(name1.compareTo(name2) < 0) { System.out.println(name1 + " scored " + score1 + " points"); System.out.println(name2 + " scored " + score2 + " points"); } else { System.out.println(name2 + " scored " + score2 + " points"); System.out.println(name1 + " scored " + score1 + " points"); } if(score1 > score2) { System.out.println(name1 + " wins!"); } else { System.out.println(name2 + " wins!"); } } } |
3.4.6 Numbers | import java.util.Scanner; public class Numbers { public static void main(String[] args) { // Start here! Scanner input = new Scanner(System.in); int num = input.nextInt(); if(num > 0) { System.out.println(“The numver is positive!”); } else if(num < 0) { System.out.println(“The numver is negative!”); } else if(num == 0) { System.out.println(“The numver is neither positive nor negative!”); } } } |
3.4.7 Salmon | @@ -0,0 +1,43 @@ import java.util.Scanner; public class Salmon { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Ask user for month of year as an integer int month = input.nextInt(); // if month is less than 3 (Jan or Feb) -- not spawning season // else if month is less than 7 (march, april, may, june) -- spring spawning season // else if month is less than 9 (july, august) -- Not spawning season // else if month is less than 12 (sept, oct, nov) -- fall spawning season // else (only month left is december) -- not spawning season if(month < 3) { System.out.println("Not spawning season"); } else if(month < 7) { System.out.println("Spring spawning season"); } else if(month < 9) { System.out.println("Not spawning season"); } else if(month < 12) { System.out.println("Fall spawning season"); } else { System.out.println("Not spawning season"); } // Note: because of the way this code is structured, // if you enter 2, every single one of these boolean // statements is true. But only the FIRST one executes! // Hence, we check for less than 3 to catch jan and feb, etc } } |
3.4.8 Berries | @@ -0,0 +1,35 @@ import java.util.Scanner; public class Berries { public static void main(String[] args) { // Ask for a berry initial Scanner input = new Scanner(System.in); String berry = input.nextLine(); // To get the input as a character, use the String method // charAt(). Use str.charAt(0) since you want the // first character // Now you can compare characters using == if(berry.charAt(0) == 'r') { System.out.println("You ordered raspberry"); } else if(berry.charAt(0) == 'h') { System.out.println("You ordered huckleberry"); } else if(berry.charAt(0) == 'g') { System.out.println("You ordered goji berry"); } else { System.out.println("Berry not recognized"); } // Use comments to list the different // branches you will need before you write the code } } |
3.4.9 Battleship | @@ -0,0 +1,60 @@ public class Battleship { private String name; // type of ship private int power; // power of attack in range [1 – 10] private int health; // health of the ship // Constructor public Battleship(String shipType, int attackPower) { name = shipType; power = attackPower; health = 100; } // Modifies the health of the battleship public void isAttacked(int attackPower) { if(attackPower < 4) { health -= 3; } else if(attackPower < 8) { health -= 5; } else { health -= 7; } } // Returns true if the health of // the ship is greater than 0 public boolean stillFloating() { if(health > 0) { return true; } else { return false; } } // Returns the power of the ship public int getPower() { return power; } // Returns string representation in the form // Battleship name public String toString() { return name + "(" + health + ")"; } } |
3.5.6 Roller Coaster | @@ -0,0 +1,27 @@ import java.util.Scanner; public class RollerCoaster { public static void main(String[] args) { Scanner input = new Scanner(System.in); int height = input.nextInt(); int age = input.nextInt(); if(height >= 42) { if(age >= 9) { System.out.println("Welcome aboard!"); } else { System.out.println("Sorry, you are not eligible to ride"); } } else { System.out.println("Sorry, you are not eligible to ride"); } } } |
3.5.7 Roller Coaster | @@ -0,0 +1,20 @@ import java.util.Scanner; public class RollerCoaster { public static void main(String[] args) { Scanner input = new Scanner(System.in); int height = input.nextInt(); int age = input.nextInt(); if(height >= 42 && age >= 9) { System.out.println("Welcome aboard!"); } else { System.out.println("Sorry, you are not eligible to ride"); } } } |
3.5.8 Divisibility | @@ -0,0 +1,23 @@ import java.util.Scanner; public class Divisibility { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(“Enter the dividend: “); int dividend = input.nextInt(); System.out.println(“Enter the divisor: “); int divisor = input.nextInt(); if(divisor != 0 && dividend % divisor == 0) { System.out.println(dividend + " is divisible by " + divisor + "!"); } else { System.out.println(dividend + " is not divisible by " + divisor + "!"); } } } |
3.5.9 Find Minimum | @@ -0,0 +1,20 @@ import java.util.Scanner; public class FindMinimum { public static void main(String[] args) { // Ask the user for three ints and // print out the minimum. Scanner input = new Scanner(System.in); System.out.println(“Enter the first integer: “); int num1 = input.nextInt(); System.out.println(“Enter the second integer: “); int num2 = input.nextInt(); System.out.println(“Enter the third integer: “); int num3 = input.nextInt(); int minimum = Math.min(num1, Math.min(num2, num3)); System.out.println("The minimum is " + minimum); } } |
3.6.5 Amusement Park | @@ -0,0 +1,54 @@ import java.util.Scanner; public class AmusementPark { static int AGE_LIMIT = 12; static int HEIGHT_LIMIT = 48; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your age: "); int age = input.nextInt(); System.out.println("Enter your height in inches: "); int height = input.nextInt(); boolean oldEnough = age >= AGE_LIMIT; boolean tallEnough = height >= HEIGHT_LIMIT; // CHANGE THIS LINE // Convert this boolean expression into its De Morgan equivalent boolean cannotRide = !oldEnough || !tallEnough; if(cannotRide) { System.out.println("You may not ride the rollercoasters."); } else { System.out.println("You may ride the rollercoasters!"); } System.out.println("Can you swim? Enter true or false."); boolean canSwim = input.nextBoolean(); System.out.println("Do you have a life jacket? Enter true or false."); boolean hasLifeJacket = input.nextBoolean(); // CHANGE THIS LINE // Convert this boolean expression into its De Morgan equivalent boolean cannotSwim = !canSwim && !hasLifeJacket; if(cannotSwim) { System.out.println("You may not swim in the pool."); } else { System.out.println("You may swim in the pool!"); } } } |
3.6.6 Odd Numbers | @@ -0,0 +1,46 @@ import java.util.Scanner; public class OddNumbers { public static void main(String[] args) { //Ask user to enter 2 positive integers Scanner input = new Scanner(System.in); System.out.println(“Enter 2 positive integers”); int num1 = input.nextInt(); int num2 = input.nextInt(); //Determine if both numbers are odd with bothOdd boolean // Do NOT remove this line! boolean bothOdd = num1 % 2 != 0 && num2 % 2 != 0; //ADD THE NEW LINE HERE boolean bothOddDeMorgan = !(num1 % 2 == 0 || num2 % 2 == 0); //Print out if both numbers are odd or not both odd if (bothOdd) { System.out.println("Both numbers are odd"); } else { System.out.println("Both numbers are NOT odd."); } //Print out if both numbers are odd or not both odd if (bothOddDeMorgan) { System.out.println("Both numbers are odd with De Morgan's Laws."); } else { System.out.println("Both numbers are NOT odd with DeMorgan's Laws."); } //Check that both Boolean values evaluate to the same value if(bothOdd == bothOddDeMorgan) { System.out.println("DeMorgan was right, again!"); } } } |
3.6.7 Odd Even | @@ -0,0 +1,15 @@ public class OddEven { // Determines if num1 and num2 are both ODD public static boolean bothOdd(int n1, int n2) { return !(n1 % 2 == 0 || n2 % 2 == 0); } // Determines if num1 and num2 are both EVEN public static boolean bothEven(int n1, int n2) { return (n1 % 2 == 0) && (n2 % 2 == 0); } } |
3.7.10 Circle | @@ -0,0 +1,53 @@ public class Circle { private int radius; private String color; private int x; private int y; public Circle(int theRadius, String theColor, int xPosition, int yPosition) { radius = theRadius; color = theColor; x = xPosition; y = yPosition; } public int getRadius() { return radius; } public int getX() { return x; } public int getY() { return y; } public String getColor() { return color; } // Implement a toString method and an equals method here! public String toString() { return (color + " circle with a radius of " + radius + " at position (" + x + ", " + y + ")"); } public boolean equals(Circle other) { if(radius == other.radius && color.equals(other.color) && x == other.x && y == other.y) { return true; } else { return false; } } } |
3.7.7 String Trace | @@ -0,0 +1,36 @@ public class StringTrace { public static void main(String[] args) { String str1 = null; String str2 = new String(“Karel”); String str3 = “Karel”; if (str1 == null) { str1 = str2; } if (str1 == str2) { System.out.println("str1 and str2 refer to the same object"); } /*if (str2 == str3) { System.out.println("str2 and str3 refer to the same object"); }*/ if (str1.equals(str2) && str2.equals(str3)) { System.out.println("str1, str2, and str3 are equal"); } /*if ((str1 == str2) && (str2 == str3)) { System.out.println("str1, str2, and str3 are the same objects"); }*/ } } |
3.7.9 Three Strings | import java.util.Scanner; public class ThreeStrings { public static void main(String[] args) { // Ask the user for three strings. // Use a Boolean variable to test the comparison of // first+second equals third // Remember since you are working with strings to // use equals() and NOT == ! Scanner input = new Scanner(System.in); System.out.print("First string? "); String string1 = input.nextLine(); System.out.print("Second string? "); String string2 = input.nextLine(); System.out.print("Third string? "); String string3 = input.nextLine(); if((string1 + string2).equals(string3)) { System.out.println(string1 + " + " + string2 + " is equal to " + string3 + "!"); } else { System.out.println(string1 + " + " + string2 + " is not equal to " + string3 + "!"); } } } |
Unit 4: Iteration
Question | Answer |
---|---|
4.1.6 TaffyTester | @@ -0,0 +1,28 @@ import java.util.Scanner; public class TaffyTester { public static void main(String[] args) { System.out.println(“Starting Taffy Timer… “); int temp = 0; Scanner input = new Scanner(System.in); while(temp < 270) { System.out.print("Enter the temperature: "); temp = input.nextInt(); if(temp < 270) { System.out.println("The mixture isn't ready yet."); } else { break; } } System.out.println("Your taffy is ready for the next step!"); } } |
4.1.7 GuessTheNumber | import java.util.Scanner; public class GuessTheNumber { // This is the secret number that will pass the autograder! static int secretNumber = 6; public static void main(String[] args) { // Allow the user to keep guessing numbers between // 1 and 10 until they guess the correct number System.out.println("I'm thinking of a number between 1 and 10."); System.out.println("See if you can guess the number!"); // This calls the static method GuessMyNumber. Notice that the method is outside // of the main method. guessMyNumber(); } public static void guessMyNumber() { // Your code goes here! int guess = 0; Scanner input = new Scanner(System.in); while(guess != secretNumber) { System.out.println("Enter your guess: "); guess = input.nextInt(); if(guess != secretNumber) { System.out.println("Try again!"); } else { System.out.println("Correct!"); break; } } } } |
4.1.8 ExtractDigits | public class ExtractDigits { public static void main(String[] args) { extractDigits(2938724); } public static void extractDigits(int num) { while(num != 0) { System.out.println(num % 10); num = num/10; } } } |
4.1.9 MaxMin | import java.util.Scanner; public class MaxMin { public static void main(String[] args) { // Your code goes here! // It is useful to plan out your steps before you get started! Scanner input = new Scanner(System.in); int smallest = 100; int largest = 0; while(true) { System.out.println("Enter a number (-1 to quit):"); int num = input.nextInt(); if(num == -1) { break; } if(num < smallest) { smallest = num; } if(num > largest) { largest = num; } System.out.println("Smallest # so far: " + smallest); System.out.println("Largest # so far: " + largest); } } } |
4.2.6 Odds | public class Odds { public static void main(String[] args) { // Your code goes here! for(int i = 0; i <= 100; i++) { if(i % 2 != 0) { System.out.println(i); } } } } |
4.2.7 Repeat100 | public class Repeat100 { public static void main(String[] args) { // Your code goes here! for(int i = 0; i < 100; i++) { System.out.println(“Hello Karel”); } } } |
4.2.8 Countdown | public class Countdown { public static void main(String[] args) { // Run this code first to see what is does. // Replace the while loop with an equivalent for loop. for(int x = 10; x > 0; x–) { System.out.println(x); } } } |
4.2.9 Odds | public class Odds { public static void main(String[] args) { // Run this code first to see what is does. // Then replace the for loop with an equivalent while loop. int x = 1 while(x <= 10) { System.out.println(x); x += 2; } } } |
4.2.10 MultiplicationTable | public class MultiplicationTable { public static void main(String[] args) { // Your code goes here! for(int i = 1; i <= 10; i++){ int ans = 4 * i; System.out.println(“4 * ” + i + ” = ” + ans); } } } |
4.3.6 Letter | import java.util.Scanner; public class Letter { public static void main(String[] args) { // Ask the user for 3 things: their word, letter they want to replace, // and replacing letter. // Call the method replaceLetter and pass all 3 of these items to it for // string processing. Scanner input = new Scanner(System.in); System.out.println("Enter your word:"); String word = input.nextLine(); System.out.println("Enter the letter you want to replace:"); String letterToReplace = input.nextLine(); System.out.println("Enter the replacing character:"); String replacer = input.nextLine(); String last = replaceLetter(word, letterToReplace, replacer); System.out.println(last); } // Modify this method so that it will take a third parameter from a user that is the String they want to //to replace letterToReplace with. This method should return the modified String. public static String replaceLetter(String word, String letterToReplace, String replacer) { int count = 0; String last = word; for(int i = 0; i < word.length(); i++) { if(word.substring(i, i+1).equals(letterToReplace)) { last = last.substring(0, i) + replacer + last.substring(i + 1); } } return last; } } |
4.3.7 Password | import java.util.Scanner; public class Password { public static void main(String[] args) { // Prompt the user to enter their password and pass their string // to the passwordCheck method to determine if it is valid. Scanner input = new Scanner(System.in); System.out.println(“Enter a password:”); String password = input.nextLine(); boolean valid = passwordCheck(password); System.out.println(valid); } public static boolean passwordCheck(String password) { // Create this method so that it checks to see that the password // is at least 8 characters long and only contains letters // and numbers. String alphanum = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890”; boolean valid; if (password.length()>= 8) { valid = true; for(int i = 0; i < password.length(); i++){ if (alphanum.indexOf(password.charAt(i)) != -1 && valid != false) { valid = true; } else { valid = false; } } } else { valid = false; } return valid; } } |
4.3.8 Palindromes | import java.util.Scanner; public class Palindromes { /** * This program lets the user input some text and * prints out whether or not that text is a palindrome. */ public static void main(String[] args) { // Create user input and let user know whether their word is a palindrome or not! Scanner input = new Scanner(System.in); System.out.println(“Type in your text:”); String word = input.nextLine(); boolean isPal = isPalindrome(word); if(isPal) { System.out.println("Your word is a palindrome!"); } else { System.out.println("Not a palindrome :("); } } /** * This method determines if a String is a palindrome, * which means it is the same forwards and backwards. * * @param text The text we want to determine if it is a palindrome. * @return A boolean of whether or not it was a palindrome. */ public static boolean isPalindrome(String text) { // Your code goes here! String reversed = reverse(text); if(text.equals(reversed)) { return true; } else { return false; } } /** * This method reverses a String. * * @param text The string to reverse. * @return The new reversed String. */ public static String reverse(String text) { String newText = ""; for(int i = text.length() - 1; i >= 0; i--) { newText += text.charAt(i); } return newText; } } |
4.3.9 Grammar | import java.util.Scanner; public class Grammar { public static void main(String[] args) { // Ask the user to enter a sentence that uses the word 2 instead of to. // Call the method useProperGrammar to process the string according to // the directions. Scanner input = new Scanner(System.in); System.out.println("Enter a sentence that uses the word 2 instead of to:"); String sentence = input.nextLine(); String last = useProperGrammar(sentence); System.out.println(last); } public static String useProperGrammar(String theText) { // Process the sentence that is sent to this method and replace every 2 // with the word to. String last = theText; int count = 0; for(int i = 0; i < last.length(); i++) { if(last.charAt(i) == '2') { last = last.substring(0, i) + "to" + last.substring(i + 1); count += 1; } } String result = last + "\n" + "Fixed " + count + " grammatical errors:"; return result; } } |
4.3.10 Teen | public class Teen { private String firstName; private String lastName; private int grade; private Boolean textMessages; // Constructor to make a teen with a first and last name, grade in school, // and whether they text message others and need to write texts to others. // This defines the state of the teen. public Teen(String theFirstName, String theLastName, int theGrade, Boolean theTextMessages) { firstName = theFirstName; lastName = theLastName; grade = theGrade; textMessages = theTextMessages; } // toString method to print out the state of teen object public String toString() { return firstName + " " + lastName + " is in grade " + grade + " and wants to send this text:"; } // Create this method so that it changes the text message // and places the word "like" in place of each space // in the message. public String teenTalk(String text) { String last = text; for(int i = 0; i < last.length(); i++) { if(last.charAt(i) == ' ') { last = last.substring(0, i) + " like " + last.substring(i + 1); i += 5; } } return last; } } |
TeenTester | import java.util.Scanner; public class TeenTester { public static void main(String[] args) { // Create a new Teen object and print it out; see the Teen class file // to see how the constructor and toString method work. Teen myFriend = new Teen(“Sonequa”, “Martin-Green”, 10, true); System.out.println(myFriend); // Ask the user to input a text message Scanner input = new Scanner(System.in); System.out.println("Enter the text message being sent:"); String message = input.nextLine(); //Call teenTalk method to translate the message to teen talk String result = myFriend.teenTalk(message); System.out.println(result); } } |
4.4.6 NumberTriangle | public class NumberTriangle { public static void main(String[] args) { // Call makeNumberTriangle makeNumberTriangle(); } // Makes an upright triangle with the numbers 1-5 public static void makeNumberTriangle() { String line = ""; // Your code goes here! for (int i=1; i<6; i++) { int num = 1; for (int j=0; j<i; j++) { System.out.print(num + " "); num += 1; } System.out.println(""); } } } |
4.4.7 TreeOfStars | public class TreeOfStars { public static void main(String[] args) { // Call makeATree makeATree(); } public static void makeATree() { // Your code goes here!!! int n = 9; for (int i=0; i1; j–) { // printing spaces System.out.print(” “); } // inner loop to handle number of columns // values changing acc. to outer loop for (int j=0; j<=i; j++ ) { // printing stars System.out.print(" *"); } // ending line after each row System.out.println(" "); } } } |
4.4.8 MultiplicationTable | public class MultiplicationTable { public static void main(String[] args) { // Call makeMultiplicationTable makeMultiplicationTable(); } // Makes a multiplcation table public static void makeMultiplicationTable() { // Your code goes here!!! // first print the top header row int a; int b; for (a = 1; a <= 10; ++a) { for (b = 1; b <= 10; ++b) { System.out.print(a*b + "\t"); } System.out.println(); } } } |
Unit 5: Writing Classes
Question | Answer |
---|---|
5.1.4 DNA | public class DNA { private String rsid; private String genotype; public DNA (String rsidOne, String genotypeOne) { rsid = rsidOne; genotype = genotypeOne; } } |
5.1.5 Employee | public class Employee { private String employee; private int id; private double salary; public Employee(String employeeName, int idNum, double salaryNum) { employee = employeeName; id = idNum; salary = salaryNum; } } |
5.1.6 Circle | public class Circle {private double radius; public Circle(double myRadius) { radius = myRadius; } public void setRadius(int myRadius){ radius = myRadius; } public double getDiameter() { return radius*2; } public double getRadius() { return radius; } public double getPerimeter() { return Math.PI*getDiameter(); } public String toString() { return "Circle with a radius of " + radius; } } |
Circle Tester | public class CircleTester {public static void main(String[] args) { Circle circ = new Circle(10); circ.setRadius(5); System.out.println(circ); System.out.println("The diameter is " + circ.getDiameter()); System.out.println("The perimeter is " + circ.getPerimeter()); } } |
5.2.5 Baseball Player | public class BaseballPlayer { private int hits; private int atBats; private String name; //Add constructor here public BaseballPlayer (String pName, int pHits, int PAtBats) { name = pName; hits = pHits; atBats = PAtBats; } public void printBattingAverage() { double battingAverage = hits / (double) atBats; System.out.println(battingAverage); } public String toString() { return name + ": " + hits + "/" + atBats; } } |
Baseball Tester | public class BaseballTester { public static void main(String[] args) { BaseballPlayer babeRuth = new BaseballPlayer(“Babe Ruth”, 2873, 8399); System.out.println(babeRuth); // Call the function printBattingAverage here babeRuth.printBattingAverage(); } } |
5.2.6 Dog | public class Dog { private String name; private int age; private double weight; // Add your constructors here public Dog(String dogName, int dogAge, double dogWeight) { name = dogName; age = dogAge; weight = dogWeight; } public Dog(String dogName, int dogAge) { name = dogName; age = dogAge; weight = 0.0; } public String toString(){ return "Name: " + name + "\nWeight: " + weight + "\nAge: " + age; } } |
Dog Tester | public class DogTester { public static void main(String[] args) { Dog golden = new Dog(“Perro”, 10, 21.9); Dog pug = new Dog(“Paul”, 5); System.out.println(golden); System.out.println(pug); } } |
5.2.6 Dog | public class Dog { private String name; private int age; private double weight; // Add your constructors here public Dog(String dogName, int dogAge, double dogWeight) { name = dogName; age = dogAge; weight = dogWeight; } public Dog(String dogName, int dogAge) { name = dogName; age = dogAge; weight = 0.0; } public String toString(){ return "Name: " + name + "\nWeight: " + weight + "\nAge: " + age; } } |
Dog Tester | public class DogTester { public static void main(String[] args) { Dog golden = new Dog(“Perro”, 10, 21.9); Dog pug = new Dog(“Paul”, 5); System.out.println(golden); System.out.println(pug); } } |
5.2.7 Student | public class Student { private String firstName; private String lastName; private int gradeLevel; private String school; /** * Constructors go here. * Check out StudentTester.java for an example of how to use * this constructor. Make sure your code matches the call in the * tester. */ public Student(String sFirstName, String sLastName, int sGradeLevel, String sSchool) { firstName = sFirstName; lastName = sLastName; gradeLevel = sGradeLevel; school = sSchool; } public Student(String sFirstName, String sLastName, int sGradeLevel) { firstName = sFirstName; lastName = sLastName; gradeLevel = sGradeLevel; if (sGradeLevel > 0 && sGradeLevel < 6) { school = “elementary school”; } if (sGradeLevel >= 6 && sGradeLevel <=8) { school = “middle school”; } if (sGradeLevel >=9 && sGradeLevel <=12) { school = “high school”; } } /** * This is a toString for the Student class. It returns a String * representation of the object, which includes the fields * in that object. * * Modify the to string to add 'and goes to _____' at the end */ public String toString() { return firstName + " " + lastName + " is in grade " + gradeLevel + " and goes to " + school; } public String getFirstName(){ return firstName; } } |
Student Tester | public class StudentTester { public static void main(String[] args) { Student alan = new Student(“Alan”, “Turing”, 11, “Liberty High School”); Student ada = new Student(“Ada”, “Lovelace”, 5); System.out.println(alan); System.out.println(ada); } } |
5.2.8 School Club | public class SchoolClub { private Student leader; private String name; private int numMembers; /* Add your constructor here * Constructor should take a leader and club name, then set * numMembers to 0. */ public SchoolClub(Student leader, String name) { this.leader = leader; this.name = name; numMembers = 0; } public void addMember() { numMembers ++; } public String toString(){ return leader.getFirstName() + " is the leader of the " + name + " club."; } } |
Student | public class Student { private String firstName; private String lastName; private int gradeLevel; private String school; /** * Constructors go here. * Check out StudentTester.java for an example of how to use * this constructor. Make sure your code matches the call in the * tester. */ public Student(String sFirstName, String sLastName, int sGradeLevel, String sSchool) { firstName = sFirstName; lastName = sLastName; gradeLevel = sGradeLevel; school = sSchool; } public Student(String sFirstName, String sLastName, int sGradeLevel) { firstName = sFirstName; lastName = sLastName; gradeLevel = sGradeLevel; if (sGradeLevel > 0 && sGradeLevel < 6) { school = “elementary school”; } if (sGradeLevel >= 6 && sGradeLevel <=8) { school = “middle school”; } if (sGradeLevel >=9 && sGradeLevel <=12) { school = “high school”; } } /** * This is a toString for the Student class. It returns a String * representation of the object, which includes the fields * in that object. * * Modify the to string to add 'and goes to _____' at the end */ public String toString() { return firstName + " " + lastName + " is in grade " + gradeLevel + " and goes to " + school; } public String getFirstName(){ return firstName; } } |
Student Tester | public class StudentTester { public static void main(String[] args) { Student alan = new Student(“Alan”, “Turing”, 11, “Liberty High School”); Student ada = new Student(“Ada”, “Lovelace”, 5); System.out.println(alan); System.out.println(ada); SchoolClub hi = new SchoolClub(ada, "hello"); System.out.println(hi); } } |
5.3.5 Activity Log | public class ActivityLog { private double numHours; private double numMiles; public ActivityLog() { numHours = 0; numMiles = 0; } public void addHours(double hours) { numHours += hours; } public void addMiles(double miles) { numMiles += miles; } public double getMiles() { return numMiles; } public double getHours() { return numHours; } } |
Activity Tracker | public class ActivityTracker { public static void main(String[] args) { ActivityLog mylog = new ActivityLog(); mylog.addMiles(5); mylog.addHours(1); System.out.print("Total Miles: "); System.out.println(mylog.getMiles()); double hoursToday = mylog.getHours(); mylog.addHours(1.5); mylog.addHours(3); double increase = mylog.getHours() - hoursToday; System.out.print("There are "); System.out.print(increase); System.out.println(" more hours today than two days ago"); } } |
5.3.6 Activity Log | public class ActivityLog { private double numHours; private double numMiles; public ActivityLog() { numHours = 0; numMiles = 0; } public void addHours(double hours) { numHours += hours; } public void addMiles(double miles) { numMiles += miles; } public double getMiles() { return numMiles; } public double getHours() { return numHours; } } |
Activity Tracker | public class ActivityTracker { public static void main(String[] args) { ActivityLog mylog = new ActivityLog(); mylog.addMiles(5); mylog.addHours(1); System.out.print("Total Miles: "); System.out.println(mylog.getMiles()); double hoursToday = mylog.getHours(); mylog.addHours(1.5); mylog.addHours(3); double increase = mylog.getHours() - hoursToday; System.out.print("There are "); System.out.print(increase); System.out.println(" more hours today than two days ago"); } } |
5.3.7 CYOA | import java.util.Scanner; public class CYOA { public static void main(String[] args) { // Start here! } } |
5.3.8 CYOA | import java.util.Scanner; public class CYOA { public static void main(String[] args) { // Start by importing your code from the previous exercise } } |
5.4.5 Messages | public class Messages { public static void main(String[] args) { // Your code here. // Create two TextMessage objects and print them out. } } |
Text Message | public class TextMessage { private String message; private String sender; private String receiver; public TextMessage(String from, String to, String theMessage) { sender = from; receiver = to; message = theMessage; } public String getSender() { return sender; } public String getReceiver() { return receiver; } public String getMessage() { return message; } public String toString() { return sender + " texted " + receiver + ": " + message; } } |
5.4.6 Dragon | public class Dragon { private int level; private String attack; // Write the constructor here! public Dragon (int level, String attack) { this.level = level; this.attack = attack; } // Put getters here public int getLevel() { return level; } public String getAttack() { return attack; } // Put other methods here public String fight() { String result = ""; for(int i = 0; i < level; i++) { result += attack; } return result; } } |
Dragon Tester | public class DragonTester { public static void main(String[] args) { // Create a Dragon here to test out the Dragon class! } } |
5.4.7 Dragon | public class Dragon { private String name; private int level; private boolean canBreatheFire; // Write the constructor here! public Dragon (String thisName, int thisLevel) { name = thisName; level = thisLevel; canBreatheFire = false; if (level >= 70) { canBreatheFire = true; } } // Put getters here public String getName() { return name; } public int getLevel() { return level; } public boolean isFireBreather() { return canBreatheFire; } // Put other methods here public void attack() { if (canBreatheFire) { System.out.println(">>>>>>>>>>"); System.out.println(">>>>>>>>>>>>>>"); System.out.println(">>>>>>>>>>>>>>"); System.out.println(">>>>>>>>>>"); } else { System.out.println(" ~ ~ ~"); } } public void gainExperience() { level += 10; if (level >= 70) { canBreatheFire = true; } } // String representation of the object public String toString() { return "Dragon " + name + " is at level " + level; } } |
Dragon Tester | public class DragonTester { public static void main(String[] args) { // Start here! } } |
5.5.5 Rectangle | public class Rectangle { private int width; private int height; /** * This is the constructor to create a Rectangle. * To create a Rectangle we need to know its width * and height. */ public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; } // Put your methods here public int getHeight() { return height; } public int getWidth() { return width; } public void setHeight(int reset) { height = reset; } public void setWidth(int reset) { width = reset; } public int getArea() { return width * height; } public int getPerimeter() { return (width + height) * 2; } /** * This method computes and prints the * area of the Rectangle. * Note it will print the area of the * Rectangle object that called it using * the dot operator! */ public void printArea() { int area = width * height; System.out.println(area); } /** * This method computes and prints the * perimeter of the Rectangle. */ public void printPerimeter() { int perimeter = 2 * width + 2 * height; System.out.println(perimeter); } /** * This is the toString method. It returns a String * representation of the object. */ public String toString() { return "Rectangle width: " + width + ", Rectangle height: " + height; } } |
Rectangle Tester | public class RectangleTester { public static void main(String[] args) { // Make some objects and print out their // areas and perimeters } } |
5.5.7 Routine | public class Routine { private double sleep; private double fun; private double school; private double sports; public Routine() { sleep = 0.0; fun = 0.0; school = 0.0; sports = 0.0; } public void setSleep(double hoursSleep) { sleep = hoursSleep; } public void setFun(double hoursFun) { fun = hoursFun; } public void setSchool(double hoursSchool) { school = hoursSchool; } public void setSports(double hoursSports) { sports = hoursSports; } public void printTotal() { System.out.println("Weekly totals \n Sleep: " + (sleep * 7)); System.out.println("School: " + (school * 7)); System.out.println("Sports: " + (sports * 7)); System.out.println("Fun: " + (fun * 7)); double gTotal = (sleep * 7)+(school * 7)+(sports * 7)+(fun * 7); System.out.println("Grand total: " + gTotal); System.out.println("Hours left over: " + (168 - gTotal)); } } |
Routine Tester | public class RoutineTester { public static void main(String[] args) { Routine myWeek = new Routine(); myWeek.setSchool(8); myWeek.setSports(3); myWeek.setSleep(8); myWeek.setFun(2); // Prints the totals for the WHOLE WEEK myWeek.printTotal(); } } |
5.6.5 Distance | public class Distance { private double miles; public Distance(double startMiles) { miles = startMiles; } public double toKilometers() { double km = miles/0.62137; return km; } public double toYards() { double yds = miles*1760; return yds; } public double toFeet() { double ft = miles*5280; return ft; } public double getMiles() { return miles; } } |
Distance Tester | public class DistanceTester { public static void main(String[] args) { // Create three Distance objects Distance KSchool = new Distance(5.0); Distance KPark = new Distance(10.0); Distance KBF = new Distance(12.0); // Convert one to yards, one to kilometers, // and the last one to feet System.out.println(KSchool.toYards()); System.out.println(KPark.toKilometers()); System.out.println(KBF.toFeet()); // Print out the converted values } } |
5.6.6 Food | public class Food { //Declare instance variables private String name; private int calories; //Create Food Constructor public Food(String thisName, int theseCalories) { name = thisName; calories = theseCalories; } //Add getter and setter methods for calories public void setName(String thisName) { name = thisName; } public void setCalories(int theseCalories) { calories = theseCalories; } public String getName() { return name; } public int getCalories() { return calories; } //Add getter and setter methods for name //Add toString method public String toString() { return name + " have " + calories + " calories"; } } |
Food Runner | import java.util.Scanner; public class FoodRunner { public static void main(String[] args) { Scanner input = new Scanner(System.in); Food hb = new Food(“Hamburgers”, 600); Food ff = new Food(“Friench Fries”, 350); Food ck = new Food(“Coke”, 200); System.out.println(hb); System.out.println("How many would you like?"); int number1 = input.nextInt(); int hbCals = hb.getCalories(); hbCals *= number1; System.out.println(ff); System.out.println("How many would you like?"); int number2 = input.nextInt(); int ffCals = ff.getCalories(); ffCals *= number2; System.out.println(ck); System.out.println("How many would you like?"); int number3 = input.nextInt(); int ckCals = ck.getCalories(); ckCals *= number3; System.out.println("Your meal with have a toal of " + (ckCals + ffCals + hbCals) + " calories"); } } |
5.7.5 Randomizer | public class Randomizer { public static int nextInt() { //Implement this method to return a random number from 1-10 return (int)(Math.random() * (9 + 1) + 1); } public static int nextInt(int min, int max) { //Implement this method to return a random integer between min and max return (int)(Math.random() * ((max-min) + 1) + min); } } |
Randomizer Tester | public class RandomizerTester { public static void main(String[] args) { System.out.println("Results of Randomizer.nextInt()"); for(int i = 0; i < 10; i++) { System.out.println(Randomizer.nextInt()); } //Initialize min and max for Randomizer.nextInt(min,max) int min = 5; int max = 10; System.out.println("\nResults of Randomizer.nextInt(5,10)"); for(int i = 0; i < 10; i++) { System.out.println(Randomizer.nextInt(min ,max)); } } } |
5.7.6 Randomizer | public class Randomizer { public static int nextInt() { //Implement this method to return a random number from 1-10 return (int)(Math.random() * (9 + 1) + 1); } public static int nextInt(int min, int max) { //Implement this method to return a random integer between min and max return (int)(Math.random() * ((max-min) + 1) + min); } } |
Rock Paper Scissors | import java.util.Scanner; public class RockPaperScissors { private static final String USER_PLAYER = “User wins!”; private static final String COMPUTER_PLAYER = “Computer wins!”; private static final String TIE = “Tie”; public static String getWinner(String user, String computer) { if(user.equals(computer)) { return TIE; } else if(user.equals("rock") && computer.equals("scissors")) { return USER_PLAYER; } else if(user.equals("paper") && computer.equals("rock")) { return USER_PLAYER; } else if(user.equals("scissors") && computer.equals("paper")) { return USER_PLAYER; } else { return COMPUTER_PLAYER; } } public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("Enter your choice (rock, paper, or scissors): "); String userChoice = ""; if(kb.hasNextLine()) { userChoice = kb.nextLine(); } if(userChoice.equals("")) { System.out.println("Thanks for playing!"); kb.close(); return; } System.out.println("User: " + userChoice); String compChoice = ""; Randomizer rand = new Randomizer(); int random = rand.nextInt(1, 3); if(random == 1) { compChoice = "rock"; } else if(random == 2) { compChoice = "paper"; } else if(random == 3) { compChoice = "scissors"; } System.out.println("Computer: " + compChoice); System.out.println(getWinner(userChoice, compChoice)); main(new String[0]); } } |
5.7.7 Player | public class Player { // Static Variables // … public static int totalPlayers; public static int maxPlayers = 10; // Public Methods public Player() { // Some code here... totalPlayers++; } // Static Methods // ... public static boolean gameFull() { if(totalPlayers >= maxPlayers) { return true; } return false; } } |
Player Tester | public class PlayerTester { public static void main(String[] args) { // Test out the Player class here! } } |
5.8.7 Scope | public class Scope { private int a; private int b; private int c; public Scope(){ a = 5; b = 10; c = 15; } public void printScope(){ //Start here System.out.println("a = " + getA()); System.out.println("b = " + getB()); System.out.println("c = " + getC()); System.out.println("d = " + getD()); System.out.println("e = " + getE()); } public int getA() { return a; } public int getB() { return b; } public int getC() { return c; } public int getD(){ int d = a + c; return d; } public int getE() { int e = b + c; return e; } } |
Scope Tester | public class ScopeTester { public static void main(String[] args) { // Start here! Scope scope = new Scope(); scope.printScope(); } } |
5.8.8 Math Operations | public class MathOperations { private static double PI = 3.14159; public static void main(String[] args) { int sumResult = sum(5, 10); int differenceResult = difference(20, 2); double productResult = product(3.5, 2); double circumferenceResult = circleCircumference(10); double areaResult = circleArea(12); } public static int sum(int one, int two) { // Printing Variables Example System.out.println("PI: " + PI); System.out.println("one: " + one); System.out.println("two: " + two); return one + two; } public static int difference(int one, int two) { // PRINT OUT VARIABLES HERE System.out.println("PI: " + PI); System.out.println("one: " + one); System.out.println("two: " + two); return one - two; } public static double product(double a, double b) { double result = a * b; // PRINT OUT VARIABLES HERE System.out.println("PI: " + PI); System.out.println("a: " + a); System.out.println("b: " + b); System.out.println("result: " + result); return result; } public static double circleCircumference(int radius) { // PRINT OUT VARIABLES HERE System.out.println("PI: " + PI); System.out.println("radius: " + radius); return 2 * radius * PI; } public static double circleArea(int radius) { double area = PI * radius * radius; // PRINT OUT VARIABLES HERE System.out.println("PI: " + PI); System.out.println("radius: " + radius); System.out.println("area: " + area); return area; } } |
5.8.9 Calculator | public class Calculator {private int total; private int value; public Calculator(int startingValue){ total = startingValue; value = 0; } public int add(int v){ total = total + v; return total; } /** * Adds the instance variable value to the total */ public int add(){ total += value; return total; } public int multiple(int v){ total *= v; return total; } public void setValue(int v){ value = v; } public int getValue(){ return value; } } |
Calculator Tester | public class CalculatorTester { public static void main(String[] args) { System.out.println("Starting at 5"); Calculator myTi = new Calculator(5); System.out.println("Adding 10 ..."); System.out.print("Should print 15: "); System.out.println(myTi.add(10)); System.out.println("Multiplying by 2 ..."); System.out.print("Should print 30: "); System.out.println(myTi.multiple(2)); System.out.println("Changing value to 20 ..."); myTi.setValue(20); System.out.print("Adding. Should print 50: "); System.out.println(myTi.add()); } } |
5.8.9 Calculator | public class Calculator {private int total; private int value; public Calculator(int startingValue){ total = startingValue; value = 0; } public int add(int v){ total = total + v; return total; } /** * Adds the instance variable value to the total */ public int add(){ total += value; return total; } public int multiple(int v){ total *= v; return total; } public void setValue(int v){ value = v; } public int getValue(){ return value; } } |
Calculator Tester | public class CalculatorTester { public static void main(String[] args) { System.out.println("Starting at 5"); Calculator myTi = new Calculator(5); System.out.println("Adding 10 ..."); System.out.print("Should print 15: "); System.out.println(myTi.add(10)); System.out.println("Multiplying by 2 ..."); System.out.print("Should print 30: "); System.out.println(myTi.multiple(2)); System.out.println("Changing value to 20 ..."); myTi.setValue(20); System.out.print("Adding. Should print 50: "); System.out.println(myTi.add()); } } |
5.9.5 Exercise | public class Exercise { public String title = “JavaScript Exercise”; public String programmingLanguage = “JavaScript”; public int points = 100; // Default constructor. public Exercise() { } // Edit code in this constructor. public Exercise(String title, String programmingLanguage, int points) { this.title = title; this.programmingLanguage = programmingLanguage; this.points = points; } public String getTitle() { return title; } } |
Exercise Tester | public class ExerciseTester { public static void main(String[] args) { Exercise exercise1 = new Exercise(); Exercise exercise2 = new Exercise(“Who needs this anyways?”, “Java”, 9001); System.out.println(exercise1.getTitle()); System.out.println(exercise2.getTitle()); } } |
5.9.6 Song | public class Song { private String artist; private String title; private int minutes; private int seconds; public Song(String artist, String title, int minutes, int seconds){ this.artist = artist; this.title = title; this.minutes = minutes; this.seconds = seconds; } /** * Returns value of artist * @return artist */ public String getArtist() { return this.artist; } /** * Sets new value of artist * @param artist Updated artist */ public void setArtist(String artist) { this.artist = artist; } /** * Returns value of title * @return title */ public String getTitle() { return this.title; } /** * Sets new value of title * @param title Updated title */ public void setTitle(String title) { this.title = title; } /** * Returns value of minutes * @return minutes */ public int getMinutes() { return this.minutes; } /** * Sets new value of minutes * @param minutes Updated minutes */ public void setMinutes(int minutes) { this.minutes = minutes; } /** * Returns value of seconds * @return seconds */ public int getSeconds() { return this.seconds; } /** * Sets new value of seconds * @param seconds Updated seconds */ public void setSeconds(int seconds) { this.seconds = seconds; } /** * Create string representation of Song for printing * @return String of the song */ @Override public String toString() { return "artist= " + artist + "\ntitle= " + title + "\nTime= " + minutes + ":" + seconds; } } |
Song Tester | public class SongTester { public static void main(String[] args) { // Start here! Song s1 = new Song(“ABBA”, “Dancing Queen”, 3, 54); System.out.println(“artist= ” + s1.getArtist()); System.out.println(“title= ” + s1.getTitle()); System.out.println(“Time= ” + s1.getMinutes() + “:” + s1.getSeconds()); Song s2 = new Song("Bruce Springsteen", "The Heart of Rock and Roll", 5, 14); System.out.println("artist= " + s2.getArtist()); System.out.println("title= " + s2.getTitle()); System.out.println("Time= " + s2.getMinutes() + ":" + s2.getSeconds()); Song s3 = new Song("Huey Lewis & the News", "The Heart of Rock and Roll", 4, 59); System.out.println("artist= " + s3.getArtist()); System.out.println("title= " + s3.getTitle()); System.out.println("Time= " + s3.getMinutes() + ":" + s3.getSeconds()); } } |
5.9.7 Fraction | public class Fraction { private int numerator; private int denominator; public Fraction(int numerator, int denominator){ this.numerator = numerator; this. denominator = denominator; } /** * Returns value of numerator * @return numerator */ public int getNumerator() { return this.numerator; } /** * Sets new value of numerator * @param numerator new numerator value */ public void setNumerator(int numerator) { this.numerator = numerator; } /** * Returns value of denominator * @return denominator */ public int getDenominator() { return this.denominator; } /** * Sets new value of denominator * @param denominator new denominator */ public void setDenominator(int denominator) { this.denominator = denominator; } /** * Updates this fraction by adding another fraction * @param other Fraction to add to existing fraction */ //Calculate by using the FractionMath class, then update //the numerator and denominator from the returned Fraction public void addFraction(Fraction other){ Fraction frac = FractionMath.add(this, other); this.numerator = frac.getNumerator(); this.denominator = frac.getDenominator(); } /** * Updates this fraction by multiplying another fraction * @param other Fraction to multiple to existing fraction */ //Calculate by using the FractionMath class, then update //the numerator and denominator from the returned Fraction public void multiplyFraction(Fraction other){ Fraction frac = FractionMath.multiply(this, other); this.numerator = frac.getNumerator(); this.denominator = frac.getDenominator(); } /** * Prints fraction as numerator / denominator * Example: 1 / 2 */ public String toString(){ return numerator + " / " + denominator; } } |
Fraction Math | public class FractionMath {/* * This is a static class that the Fraction class will use. * No updates are needed. */ public static Fraction add(Fraction frac1, Fraction frac2){ int numerator = frac1.getNumerator() * frac2.getDenominator() + frac2.getNumerator() * frac1.getDenominator(); int denominator = frac1.getDenominator() * frac2.getDenominator(); Fraction solution = new Fraction(numerator, denominator); return solution; } public static Fraction multiply(Fraction frac1, Fraction frac2){ int numerator = frac1.getNumerator() * frac2.getNumerator(); int denominator = frac1.getDenominator() * frac2.getDenominator(); Fraction solution = new Fraction(numerator, denominator); return solution; } } |
Fraction Tester | public class FractionTester { public static void main(String[] args) { Fraction first = new Fraction(3, 4); Fraction half = new Fraction(1, 2); System.out.println(first); System.out.print("Multiplying: "); System.out.println(half); first.multiplyFraction(half); System.out.println("Answer: " + first); System.out.println(); System.out.print("Adding: "); System.out.println(half); first.addFraction(half); System.out.println("Answer: " + first); } } |
Unit 6: Array
Question | Answer |
---|---|
6.1.6 First Array | public class FirstArray { public static void main(String[] args) { // Create the 3 arrays here String[] cityNames = { “Las Vegas”, “Minsk”, “Sao Paulo” }; int[] temps = { 104, 73, 80 }; double[] precip = { 4.17, 26.7, 55.0 }; // Print all 3 arrays according to the output in the description System.out.println(cityNames[0] + ” has an average annual precipitation of ” + precip[0] + ” inches.”); System.out.println(cityNames[0] + ” has an average annual high temp of ” + temps[0] + ” degrees Fahrenheit.”); System.out.println(cityNames[1] + ” has an average annual precipitation of ” + precip[1] + ” inches.”); System.out.println(cityNames[1] + ” has an average annual high temp of ” + temps[1] + ” degrees Fahrenheit.”); System.out.println(cityNames[2] + ” has an average annual precipitation of ” + precip[2] + ” inches.”); System.out.println(cityNames[2] + ” has an average annual high temp of ” + temps[2] + ” degrees Fahrenheit.”); } } |
6.1.7 Scores | public class Scores { public static void main(String[] args) { // Start here! int[] scores = { 80, 95, 82, 67, 100 }; for(int i = 0; i < 5; i++) { System.out.println(scores[i]); } System.out.println(); scores[2] = 72; scores[4] = 95; for(int i = 0; i < 5; i++) { System.out.println(scores[i]); } } } |
6.1.8 Last Element | public class LastElement { public static void main(String[] args) { String[] arr = new String[]{“hello”, “my name”, “world”, “Karel”}; //get and print the last element of the array String last = getLastElement(arr); System.out.println(“The last element of the String array is: ” + last); } public static String getLastElement(String[] arr) { // Your code goes here! return arr[arr.length - 1]; } } |
6.1.9 Snap Shot | public class SnapShot { public static void main(String[] args) { // Start here! String[] arr = { “Welcome”, “to”, “the snap shot”, “app!” }; for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } System.out.println(); arr[0] = “Upgrade”; arr[arr.length – 1] = “premium app!”; for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } |
6.2.7 Print Array | public class PrintArray { public static void main(String[] args) { String[] arr = new String[]{“a”, “b”, “c”}; printArr(arr); } public static void printArr(String[] arr) { // Print everything in the array on its own line for(int i = 0; i < arr.length; i ++) { System.out.println(arr[i]); } } } |
6.2.8 Print Odd | public class PrintOdd { public static void main(String[] args) { int[] oddIndexArray = new int[] {1, 2, 3, 4, 5}; printOddIndices(oddIndexArray); } public static void printOddIndices(int[] arr) { // your code goes here! for(int i = 0; i < arr.length; i ++) { if(i % 2 != 0) { System.out.println(arr[i]); } } } } |
6.2.9 Matching String | public class MatchingString { private static String[] arr = {"Hello", "Karel", "CodeHS!"}; public static int findString(String myString) { // your code goes here! for(int i = 0; i < arr.length; i++) { if(arr[i] == myString) { return i; } } return -1; } } |
Matching String Tester | public class MatchingStringTester { public static void main(String[] args) { System.out.println(MatchingString.findString(“Karel”)); } } |
6.2.10 Fibonacci | public class Fibonacci { public static void main(String[] args) { //number of elements to generate in the sequence int max = 15; // create the array to hold the sequence of Fibonacci numbers int[] sequence = new int[max]; //create the first 2 Fibonacci sequence elements sequence[0] = 0; sequence[1] = 1; //create the Fibonacci sequence and store it in int[] sequence for(int i = 2; i < sequence.length; i++) { sequence[i] = sequence[i - 1] + sequence[i - 2]; } //print the Fibonacci sequence numbers for(int i = 0; i < sequence.length; i++) { System.out.print(sequence[i] + " "); } System.out.println("\nIndex position of 55 is: " + findIndex(sequence, 55)); } // This method finds the index of an element in an array public static int findIndex (int[] arr, int n) { // your code goes here for(int i = 0; i < arr.length; i++) { if(arr[i] == n) { return i; } } return -1; } } |
6.3.6 Print Odds | public class PrintOdds { public static void main(String[] args) { int[ ] values = {17, 34, 56, 2, 19, 100}; for (int value : values) { if (value % 2 == 1) System.out.println(value + " is odd"); } } } |
6.3.7 Largest Value | public class LargestValue { public static void main(String[] arg) { { int[] values = {32, 56, 79, 2, 150, 37}; int highestValue = findMax(values); System.out.println("The highest score is " + highestValue); } } public static int findMax(int[] numbers) { int maxSoFar = numbers[0]; // for each loop to rewrite as for loop for (int i = 0; i < numbers.length; i++) { if (numbers[i] > maxSoFar) { maxSoFar = numbers[i]; } } return maxSoFar; } } |
6.3.8 Class Roster | public class ClassRoster { public static void main(String[] args) { Student julian = new Student(“Julian”, “Jones”, 9); Student larisa = new Student(“Larisa”, “Torres”, 10); Student amada = new Student(“Amada”, “Robin”, 10); Student mikka = new Student(“Mikka”, “Leads”, 9); Student jay = new Student(“Jay”, “Khalil”, 10); Student[] classroom = {julian, larisa, amada, mikka, jay}; // for each for printing goes here for(Student student : classroom) { System.out.println(student.getFirstName() + " " + student.getLastName() + " is in grade " + student.getGradeLevel()); } } } |
Student | /** The Student class holds data about a student. The fields are firstName, lastName, and grade. */ public class Student { // Attributes private String firstName; private String lastName; private int gradeLevel; // Constructor public Student(String fName, String lName, int grade) { firstName = fName; lastName = lName; gradeLevel = grade; } public String getFirstName() { return firstName; } // new getter public String getLastName() { return lastName; } // new getter public int getGradeLevel() { return gradeLevel; } /* public String toString() { return firstName + ” ” + lastName + ” is in grade: ” + gradeLevel; } */ } |
6.3.9 Array Average | public class ArrayAverage { private int[] values; public ArrayAverage(int[] theValues) { values = theValues; } public double getAverage() { // your code goes here! int total = 0; for(int val : values) { total += val; } double avg = (double)total / values.length; return avg; } } |
Array Average Tester | public class ArrayAverageTester { public static void main(String[] args) { int[] numArray = {12, 17, 65, 7, 30, 88}; // Create an ArrayAverage object and print the result ArrayAverage hi = new ArrayAverage(numArray); double avglast = hi.getAverage(); System.out.println("The average of the array is " + avglast); } } |
6.4.6 Median | import java.util.*; public class Median { public static void main(String[] args) { int[] numbers1 = {12, 75, 3, 17, 65, 22}; System.out.print("The median value of the EVEN array is " + median(numbers1)); int[] numbers2 = {12, 75, 3, 17, 65, 22, 105}; System.out.print("\nThe median value of the ODD array is " + median(numbers2)); } public static double median(int[] arr) { // your code goes here! Arrays.sort(arr); if(arr.length % 2 == 0) { return (double)(arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2; } else { return arr[arr.length / 2]; } } } |
6.4.7 Last Multiple Of Three | public class LastMultipleOfThree { public static void main(String[] args) { int[] numbers1 = {76, 75, 3, 17, 12, 22, 7}; System.out.print("The following index holds the LAST multiple of 3: " + findMultipleOfThree(numbers1)); } public static int findMultipleOfThree(int[] arr) { // your code goes here! for(int i = arr.length - 1; i >= 0; i--) { if(arr[i] % 3 == 0) { return i; } } return -1; } } |
6.4.8 Classroom | import java.util.Arrays; public class Classroom { Student[] students; int numStudentsAdded; public Classroom(int numStudents) { students = new Student[numStudents]; numStudentsAdded = 0; } public Student getMostImprovedStudent() { // your code goes here! int mostImprovement = 0; int mostImprovedIndex = 0; for(int i = 0; i < students.length; i++) { if(students[i] != null && students[i].getExamRange() > mostImprovement) { mostImprovement = students[i].getExamRange(); mostImprovedIndex = i; } } return students[mostImprovedIndex]; } public void addStudent(Student s) { students[numStudentsAdded] = s; numStudentsAdded++; } public void printStudents() { for(int i = 0; i < students.length; i++) { if(students[i] != null) { System.out.println(students[i]); } } } } |
Classroom Tester | public class ClassroomTester { public static void main (String[] args) { Classroom c = new Classroom(2); Student ada = new Student("Ada", "Lovelace", 12); ada.addExamScore(44); ada.addExamScore(65); ada.addExamScore(77); Student alan = new Student("Alan", "Turing", 11); alan.addExamScore(38); alan.addExamScore(24); alan.addExamScore(31); // add students to classroom c.addStudent(ada); c.addStudent(alan); c.printStudents(); Student mostImproved = c.getMostImprovedStudent(); System.out.println("The most improved student is " + mostImproved.getName()); } } |
Student | import java.util.Arrays; public class Student { private static final int NUM_EXAMS = 4; private String firstName; private String lastName; private int gradeLevel; private double gpa; private int[] exams; private int numExamsTaken; /** * This is a constructor. A constructor is a method * that creates an object -- it creates an instance * of the class. What that means is it takes the input * parameters and sets the instance variables (or fields) * to the proper values. * * Check out StudentTester.java for an example of how to use * this constructor. */ public Student(String fName, String lName, int grade) { firstName = fName; lastName = lName; gradeLevel = grade; exams = new int[NUM_EXAMS]; numExamsTaken = 0; } public int getExamRange() { // your code goes here! Arrays.sort(exams); return exams[exams.length - 1] - exams[0]; } public String getName() { return firstName + " " + lastName; } public void addExamScore(int score) { exams[numExamsTaken] = score; numExamsTaken++; } // This is a setter method to set the GPA for the Student. public void setGPA(double theGPA) { gpa = theGPA; } /** * This is a toString for the Student class. It returns a String * representation of the object, which includes the fields * in that object. */ public String toString() { return firstName + " " + lastName + " is in grade: " + gradeLevel; } } |
6.4.9 Car Model | class CarModel { private String name; private int speed; public CarModel(String theName, int theSpeed) { this.name = theName; this.speed = theSpeed; } public String getName() { return this.name; } public int getSpeed() { return this.speed; } public String toString() { return this.name + ” with a top speed of ” + this.speed; } } |
Car Showroom | public class CarShowroom { public static void main (String[] args) { CarShowroom showroom = new CarShowroom(7); showroom.spaces[0] = new CarModel(“Mustang”, 157); showroom.spaces[1] = new CarModel(“Camaro”,155); showroom.spaces[3] = new CarModel(“Corvette”, 194); showroom.spaces[6] = new CarModel(“Porshe”, 210); // print out what is in the showroom System.out.println(showroom); // test output System.out.println("Index of Mustang should be 0 and is " + showroom.findCarSpace("Mustang")); System.out.println("Index of Corvette should be 3 and is " + showroom.findCarSpace("Corvette")); System.out.println("Index of Miata should be -1 and is " + showroom.findCarSpace("Miata")); System.out.println("\nOriginal Car Showroom:"); System.out.println(showroom); showroom.consolidate(); System.out.println("Car Showroom after cars have been consolidated:"); System.out.println(showroom); } private CarModel[] spaces; // constructor for number of spaces in showroom public CarShowroom(int numParkingSpaces) { spaces = new CarModel[numParkingSpaces]; } // Returns index of space that contains the car with the specified model // and -1 if no car in the showroom is that model.No two cars in the showroom are the same model. public int findCarSpace(String name) { // your code goes here for(int i = 0; i < spaces.length; i++) { if(spaces[i] != null && spaces[i].equals(name)) { return i; } } return -1; } // Consolidates cars in the showroom so that there are no gaps // in the parking spaces so that it’s easier to move new models in public void consolidate() { int nextSpace = 0; for(int i = 0; i < spaces.length; i++) { if(spaces[i] != null) { spaces[nextSpace] = spaces[i]; nextSpace++; } } for(int i = nextSpace; i < spaces.length; i++) spaces[i] = null; } public String toString() { String result = “”; CarModel sp = null; // iterate through the spaces for (int i = 0; i < spaces.length; i++) { sp = spaces[i]; result = result + "Space " + i + " has a "; // locate empty spaces if (sp == null) { result = result + " null \n"; } else result = result + sp.toString() + "\n"; } return result; } } |
Unit 7: Array List
Question | Answer |
---|---|
7.1.6 Agency | import java.util.ArrayList; public class Agency { public static void main(String[] args) { //Initialize your ArrayLists here! ArrayList companyName = new ArrayList(); ArrayList contractValue = new ArrayList(); } } |
7.1.7 Car | public class Car { String name; String model; int cost; public Car(String name, String model, int cost) { this.name = name; this.model = model; this.cost = cost; } } |
Car Tracker | import java.util.ArrayList; public class CarTracker { public static void main(String[] args) { //Initialize your ArrayList here: ArrayList inventory = new ArrayList(); } } |
7.2.6 Numbers | import java.util.ArrayList; public class Numbers { public static void main(String[] args) { ArrayList numbers = new ArrayList(); // Add 5 numbers to numbers numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); // Print out the first element in `numbers` System.out.println(numbers.get(0)); } } |
7.2.7 Evens | import java.util.ArrayList; public class Evens { public static void main(String[] args) { ArrayList evens = new ArrayList(); for(int i = 2; i <= 100; i += 2) { evens.add(i); } printArray(evens); } //Don't alter this method! It will print your array in the console public static void printArray(ArrayList<Integer> array) { System.out.println("Array:"); for(int name : array) { System.out.print(name + " "); } } } |
7.2.8 Class List Tester | public class ClassListTester { public static void main(String[] args) { //You don’t need to change anything here, but feel free to add more Students! Student alan = new Student(“Alan”, 11); Student kevin = new Student(“Kevin”, 10); Student annie = new Student(“Annie”, 12); System.out.println(Student.printClassList()); } } |
Student | import java.util.ArrayList; public class Student { private String name; private int grade; //Implement classList here: private static ArrayList<Student> classList = new ArrayList<Student>(); public Student(String name, int grade) { this.name = name; this.grade = grade; classList.add(this); } public String getName() { return this.name; } /*Don't change the code in this method! This method will print out all the Student names in the classList Array */ public static String printClassList() { String names = ""; for(Student name : classList) { names += name.getName() + "\n"; } return "Student Class List:\n" + names; } } |
7.2.9 Student | import java.util.ArrayList; public class Student { private String name; private int grade; //Implement classList here: private static ArrayList classList = new ArrayList(); public Student(String name, int grade) { this.name = name; this.grade = grade; classList.add(this); } public String getName() { return this.name; } //Add the static methods here: public static String getLastStudent() { return classList.get(classList.size() - 1).getName(); } public static int getClassSize() { return classList.size(); } public static void addStudent(int index, Student student) { classList.remove(classList.size() - 1); classList.add(index, student); } public static String getStudent(int index) { return classList.get(index).getName(); } public static String printClassList() { String names = ""; for(Student name : classList) { names += name.getName() + "\n"; } return "Student Class List:\n" + names; } } |
Class List Tester | public class ClassListTester { public static void main(String[] args) { //You don’t need to change anything here, but feel free to add more Students! Student alan = new Student(“Alan”, 11); Student kevin = new Student(“Kevin”, 10); Student annie = new Student(“Annie”, 12); System.out.println(Student.printClassList()); System.out.println(Student.getLastStudent()); System.out.println(Student.getStudent(1)); Student.addStudent(2, new Student("Trevor", 12)); System.out.println(Student.printClassList()); System.out.println(Student.getClassSize()); } } |
7.3.6 Odds | import java.util.ArrayList; public class Odds { public static void main(String[] args) { ArrayList odds = new ArrayList(); // Pre-load the array list with values. for(int index = 1; index < 101; index++) { odds.add(index); odds.add(index); } //call removeEvens on the array above! removeEvens(odds); } public static void removeEvens(ArrayList array) { for(int i = 0; i < array.size(); i++) { if(array.get(i) % 2 == 0) { array.remove(i); i–; } } for(int i = 0; i < array.size(); i++) { System.out.println(array.get(i)); } } } |
7.3.7 Array List Methods | import java.util.ArrayList; public class ArrayListMethods { public static void print(ArrayList array) { for(String s : array) { System.out.println(s); } } public static void condense(ArrayList array) { for(int i = 0; i < array.size() – 1; i++) { array.set(i, array.get(i) + array.get(i + 1)); array.remove(i + 1); } } public static void duplicate(ArrayList array) { for(int i = 0; i < array.size(); i += 2) { array.add(i, array.get(i)); } } } |
Array List Methods Tester | import java.util.ArrayList; public class ArrayListMethodsTester { public static void main(String[] args) { ArrayList stringArray = new ArrayList(); stringArray.add(“This”); stringArray.add(“is”); stringArray.add(“an”); stringArray.add(“ArrayList”); stringArray.add(“of”); stringArray.add(“Strings”); ArrayListMethods.print(stringArray); System.out.println("\nArrayList is condensing:"); ArrayListMethods.condense(stringArray); ArrayListMethods.print(stringArray); System.out.println("\nArrayList is duplicating:"); ArrayListMethods.duplicate(stringArray); ArrayListMethods.print(stringArray); } } |
7.3.8 Geo Location | /* This class stores information about a location on Earth. Locations are specified using latitude and longitude. The class includes a method for computing the distance between two locations. * This implementation is based off of the example from Stuart Reges at the University of Washington. */ public class GeoLocation { // Earth radius in miles public static final double RADIUS = 3963.1676; private double latitude; private double longitude; private String name; /** * Constructs a geo location object with given latitude and longitude */ public GeoLocation(String name, double theLatitude, double theLongitude) { this.name = name; latitude = theLatitude; longitude = theLongitude; } public String getName() { return this.name; } /** * Returns the latitude of this geo location */ public double getLatitude() { return latitude; } /** * returns the longitude of this geo location */ public double getLongitude() { return longitude; } // returns a string representation of this geo location public String toString() { return name + " (" + latitude + ", " + longitude + ")"; } // returns the distance in miles between this geo location and the given // other geo location public double distanceFrom(GeoLocation other) { double lat1 = Math.toRadians(latitude); double long1 = Math.toRadians(longitude); double lat2 = Math.toRadians(other.latitude); double long2 = Math.toRadians(other.longitude); // apply the spherical law of cosines with a triangle composed of the // two locations and the north pole double theCos = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(long1 - long2); double arcLength = Math.acos(theCos); return arcLength * RADIUS; } } |
Road Trip | import java.util.ArrayList; public class RoadTrip { private ArrayList places; public RoadTrip() { this.places = new ArrayList<GeoLocation>(); } // Create a GeoLocation and add it to the road trip public void addStop(String name, double latitude, double longitude) { places.add(new GeoLocation(name, latitude, longitude)); } // Get the total number of stops in the trip public int getNumberOfStops() { return places.size(); } // Get the total miles of the trip public double getTripLength() { double total = 0; for(int i = 1; i < places.size(); i++) { total += places.get(i).distanceFrom(places.get(i - 1)); } return total; } // Return a formatted toString of the trip public String toString() { String list = ""; for(int i = 0; i < places.size(); i++) { list += i + 1 + ". " + places.get(i).toString() + "\n"; } return list; } } |
Road Trip Tester | public class RoadTripTester { public static void main(String[] args) { RoadTrip rt = new RoadTrip(); rt.addStop(“San Francisco”, 37.7833, -122.4167); rt.addStop(“Los Angeles”, 34.052235, -118.243683); rt.addStop(“Las Vegas”, 36.114647, -115.172813); System.out.println(rt); System.out.println("Stops: " + rt.getNumberOfStops()); System.out.println("Total Miles: " + rt.getTripLength()); } } |
7.4.5 is Equal | import java.util.ArrayList; public class isEqual { public static void main(String[] args) { //This code is just to test your equals method ArrayList list1 = new ArrayList(); list1.add(10); list1.add(9); list1.add(5); list1.add(2); list1.add(9); ArrayList list2 = new ArrayList(); list2.add(10); list2.add(9); list2.add(5); list2.add(2); list2.add(9); boolean isEqual = equals(list1, list2); System.out.println(“List 1 is equal to List 2: ” + isEqual); ArrayList list3 = new ArrayList(); list3.add(1); list3.add(9); list3.add(5); list3.add(2); list3.add(9); boolean isEqual2 = equals(list2, list3); System.out.println(“List 2 is equal to List 3: ” + isEqual2); } //Write your method here! public static boolean equals(ArrayList<Integer> array1, ArrayList<Integer> array2) { if(array1.size() != array2.size()) { return false; } int size = array1.size(); for(int i = 0; i < size; i++) { if(array1.get(i) != array2.get(i)) { return false; } } return true; } } |
7.4.6 Airline Ticket | public class AirlineTicket { private String[] seats = {“A”,”B”,”C”,”D”,”E”,”F”}; private String name; private String seat; private int boardingGroup; private int row; public AirlineTicket(String name, String seat, int boardingGroup, int row) { this.name = name; if(isValidSeat(seat)) { this.seat = seat; } this.boardingGroup = boardingGroup; this.row = row; } private boolean isValidSeat(String seat) { boolean isValidSeat = false; for(String elem: seats) { if(seat.equals(elem)) { isValidSeat = true; } } return isValidSeat; } public String getSeat() { return this.seat; } public String getName() { return this.name; } public int getBoardingGroup() { return this.boardingGroup; } public int getRow() { return this.row; } public String toString() { return name + " Seat: " +seat + " Row: " + row + " Boarding Group: " + boardingGroup; } } |
Airline Ticket Tester | import java.util.ArrayList; public class AirlineTicketTester { public static void main(String[] args) { ArrayList tickets = new ArrayList(); //This creates a randomized list of passengers addPassengers(tickets); for(AirlineTicket elem: tickets) { System.out.println(elem); } //This creates a TicketOrganizer object TicketOrganizer ticketOrganizer = new TicketOrganizer(tickets); //These are the methods of the ticketOrganizer in action System.out.println("\nPassengers Ordered by Boarding Group:"); ticketOrganizer.printPassengersByBoardingGroup(); System.out.println("\nPassengers in line who can board together:"); ticketOrganizer.canBoardTogether(); } //Do not touch this method! It is adding random passengers to the AirlineTicket array public static void addPassengers(ArrayList<AirlineTicket> tickets) { String[] seats = {"A","B","C","D","E","F"}; for(int index = 0; index< 15; index++) { int random = (int)(Math.random() * 5); AirlineTicket ticket = new AirlineTicket("Passenger " + (index+1), seats[random], ((int)(Math.random()*5)+1), ((int)(Math.random()*8)+1)); tickets.add(ticket); } } } |
Ticket Organizer | import java.util.ArrayList; public class TicketOrganizer { private ArrayList tickets; public TicketOrganizer(ArrayList<AirlineTicket> theTickets) { this.tickets = theTickets; } public ArrayList<AirlineTicket> getTickets() { return this.tickets; } public void printPassengersByBoardingGroup() { for(int i = 1; i <= 5; i++) { System.out.println("Boarding Group " + i + ":"); for(int j = 0; j < tickets.size(); j++) { if(tickets.get(j).getBoardingGroup() == i) { System.out.println("Passenger " + (j + 1)); } } } } public void canBoardTogether() { boolean somePassengersCanBoard = false; for(int i = 0; i < tickets.size() - 1; i++) { if(tickets.get(i).getBoardingGroup() == tickets.get(i + 1).getBoardingGroup() && tickets.get(i).getRow() == tickets.get(i + 1).getRow()) { System.out.println("Passenger " + i + 1 + " can board with Passenger " + i + 2 + "."); somePassengersCanBoard = true; } } if(!somePassengersCanBoard) { System.out.println("There are no passengers with the same row and boarding group."); } } } |
7.4.7 Billboard | import java.util.ArrayList; public class Billboard { private ArrayList top10 = new ArrayList(); public void add(Musician m) { if(!m.getIsPlatinum()) { System.out.println("Sorry, " + m.getName() + " does not qualify for Top 10"); return ; } if(top10.size() < 10) { top10.add(m); } else { replace(m); } } public void replace(Musician toAdd) { int minWeeksTop40 = 1000; int minWeeksTop40Index = 0; for(int i = 0; i < top10.size(); i++) { Musician m = top10.get(i); if(m.getWeeksInTop40() < minWeeksTop40) { minWeeksTop40 = m.getWeeksInTop40(); minWeeksTop40Index = i; } } if(toAdd.getWeeksInTop40() <= minWeeksTop40) { System.out.println("Sorry, " + toAdd.getName() + " has less weeks in the Top 40 than the other musicians."); } else { System.out.println("The musician " + top10.get(minWeeksTop40Index).getName() + " has been replaced by " + toAdd.getName() + "."); top10.set(minWeeksTop40Index, toAdd); } } //Don't make alterations to this method! public void printTop10() { System.out.println(top10); } } |
Billboard Tester | public class BillboardTester { public static void main(String[] args) { Billboard top10 = new Billboard(); top10.add(new Musician(“Beyonce”, 316, 100000000)); top10.add(new Musician(“The Beatles”, 365, 600000000)); top10.add(new Musician(“Drake”, 425, 150000000)); top10.add(new Musician(“Pink Floyd”, 34, 250000000)); top10.add(new Musician(“Mariah Carey”, 287, 200000000)); top10.add(new Musician(“Rihanna”, 688, 250000000)); top10.add(new Musician(“Queen”, 327, 170000000)); top10.add(new Musician(“Ed Sheeran”, 536, 150000000)); top10.add(new Musician(“Katy Perry”, 317, 143000000)); top10.add(new Musician(“Justin Bieber”, 398, 140000000)); //This musician should not be added to the top10 because they don't have enough records sold top10.add(new Musician("Karel the Dog", 332, 60)); //This musician should replace the artist with the least Weeks on the top 40 charts. top10.add(new Musician("Tracy the Turtle", 332, 150000000)); //This musician should not replace an artist, but is a Platinum artist top10.add(new Musician("Alex Eacker", 100, 23400000)); top10.printTop10(); } } |
Musician | public class Musician { private String name; private int weeksInTop40; private int albumsSold; private boolean isPlatinum;; public Musician(String name, int weeksInTop40, int albumsSold) { this.name = name; this.weeksInTop40 = weeksInTop40; this.albumsSold = albumsSold; setPlatinum(albumsSold); } public void setPlatinum(int albumsSold) { if(albumsSold >= 1000000) { isPlatinum = true; } else { isPlatinum = false; } } public int getWeeksInTop40() { return this.weeksInTop40; } public String getName() { return this.name; } public boolean getIsPlatinum() { return isPlatinum; } public String toString() { return this.name; } } |
7.4.8 Data Purge | import java.util.ArrayList; public class DataPurge { public static void removeDuplicates(ArrayList list) { ArrayList existing = new ArrayList(); for(int i = 0; i < list.size(); i++) { String email = list.get(i); if(existing.indexOf(email) != -1) { list.remove(i); i--; } existing.add(email); } } public static void removeAOL(ArrayList<String> list) { for(int i = 0; i < list.size(); i++) { if(list.get(i).indexOf("[email protected].com") > -1) { System.out.println("removing " + list.get(i)); list.remove(i); i--; } } } public static boolean containsOnlyEmails(ArrayList<String> list) { for(int i = 0; i < list.size(); i++) { if(list.get(i).indexOf("@") == -1 || list.get(i).indexOf(".") == -1) { return false; } } return true; } } |
Data Purge Tester | import java.util.ArrayList; public class DataPurgeTester { public static void main(String[] args) { ArrayList emails = new ArrayList(); addEmails(emails); System.out.println(“List is all emails: ” +DataPurge.containsOnlyEmails(emails)); DataPurge.removeDuplicates(emails); DataPurge.removeAOL(emails); System.out.println(emails); } public static void addEmails(ArrayList<String> emails) { emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("mailarc[email protected].com"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("gordonjcp[email protected].com"); emails.add("[email protected]"); } } |
7.5.4 Array List Search | import java.util.ArrayList; public class ArrayListSearch { public static void main(String[] args) { ArrayList array = new ArrayList(); array.add(4.5); array.add(6.7); array.add(5.0); array.add(2.9); array.add(7.0); System.out.println(search(array, 5.0)); } public static int search(ArrayList array, double key) { int i = 0; while(i < array.size()) { if(array.get(i) == key) { return i; } i++; } return -1; } } |
7.5.5 Fantasy Football | import java.util.ArrayList; import java.util.Scanner; public class FantasyFootball { public static void main(String[] args) { ArrayList availablePlayers = new ArrayList(); addPlayers(availablePlayers); String[] team = new String[5]; Scanner sc = new Scanner(System.in); for(int i = 0; i < 5; i++) { System.out.println("Enter Player you would like on your team: "); String player = sc.nextLine(); int playerIndex = search(availablePlayers, player); if(playerIndex > -1) { System.out.println("Great! That player is added to your team!"); team[i] = player; availablePlayers.remove(playerIndex); } else { System.out.println("That player is not available, please pick another player."); i--; } System.out.println(""); } System.out.println("Your team is:"); for(int i = 0; i < 5; i++) { System.out.println(team[i]); } } public static int search(ArrayList<String> array, String player) { for(int i = 0; i < array.size(); i++) { if(array.get(i).equals(player)) { return i; } } return -1; } public static void addPlayers(ArrayList<String> array) { array.add("Cam Newton"); array.add("Antonio Brown"); array.add("Leveon Bell"); array.add("Patrick Mahomes"); array.add("Saquon Barkley"); array.add("Mike Evans"); array.add("Odell Beckham Jr."); array.add("Travis Kelce"); array.add("Baker Mayfield"); array.add("Michael Thomas"); array.add("Julio Jones"); array.add("Ezekial Elliott"); array.add("Alvin Kamara"); array.add("Davante Adams"); array.add("Aaron Rogers"); } } |
7.6.4 Selection Sort | import java.util.Arrays; public class SelectionSort { public static void main(String[] args) { int[] array1 = {9, 8, 7, 6, 5, 4, 3, 2, 1}; int[] array2 = {5, 6, 4, 8, 9, 7, 3, 1, 2}; System.out.print("First array: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array: "); System.out.println(Arrays.toString(array2)); System.out.println(); // sort first array selectionSort(array1); // sort second array selectionSort(array2); System.out.print("First array sorted: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array sorted: "); System.out.println(Arrays.toString(array2)); } /* * Selection sort takes in an array of integers and * returns a sorted array of the same integers. */ public static int[] selectionSort(int[] arr) { int swaps = 0; int currentMinIndex; for(int i = 0; i < arr.length - 1; i++) { currentMinIndex = i; for(int j = i + 1; j < arr.length; j++) { if(arr[j] < arr[currentMinIndex]) { currentMinIndex = j; } } // swap numbers if needed if(i != currentMinIndex) { int temp = arr[currentMinIndex]; arr[currentMinIndex] = arr[i]; arr[i] = temp; swaps++; } } // Print out the number of swaps that took place here // before returning arr System.out.println(swaps); return arr; } } |
7.6.9 Insertion Sort | import java.util.Arrays; public class InsertionSort { public static void main(String[] args) { int[] array1 = {9, 8, 7, 6, 5, 4, 3, 2, 1}; int[] array2 = {5, 6, 4, 8, 9, 7, 3, 1, 2}; System.out.print("First array: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array: "); System.out.println(Arrays.toString(array2)); System.out.println(); // sort first array insertionSort(array1); // sort second array insertionSort(array2); System.out.print("First array sorted: "); System.out.println(Arrays.toString(array1)); System.out.print("Second array sorted: "); System.out.println(Arrays.toString(array2)); } /* * Insertion sort takes in an array of integers and * returns a sorted array of the same integers. */ public static void insertionSort(int[] arr) { for(int i = 0; i < arr.length; i++) { int value = arr[i]; int j; for(j = i - 1; j >= 0 && arr[j] < value; j--) { arr[j + 1] = arr[j]; } arr[j + 1] = value; } } } |
7.6.10 Insertionv Selection | public class InsertionvSelection { public static void main(String[] args) { /* This program evaluates the speed that Selection and Insertion sort are able to sort different arrays. What do you notice about the difference in speed? Why do you think that’s the case? */ //Try changing the size of the array by changing the value of makeReverseArray() //Does that change the results? int[] reverse = makeReverseArray(100); System.out.println("Reversed Array:"); printArray(reverse); long startTime = System.nanoTime(); selectionSort(reverse); long endTime = System.nanoTime(); long timeElapsed = endTime - startTime; System.out.println("\nSelection Sort on Reversed Array:"); printArray(reverse); System.out.println("Time elapsed: " + timeElapsed + " nanoseconds."); //Try changing the size of the array by changing the value of makeReverseArray() //Does that change the results? int[] reverse2 = makeReverseArray(100); System.out.println("\nReversed Array:"); printArray(reverse2); long newstartTime = System.nanoTime(); insertionSort(reverse2); long newendTime = System.nanoTime(); long newtimeElapsed = newendTime - newstartTime; System.out.println("\nInsertion Sort on Reversed Array:"); printArray(reverse2); System.out.println("Time elapsed: " + newtimeElapsed + " nanoseconds.\n"); checkSpeed(timeElapsed, newtimeElapsed); System.out.println("\n=================================================="); //Try changing the size of the array by changing the value of makeAlmostSortedArray() //Does that change the results? int[] almostSorted = makeAlmostSortedArray(100); System.out.println("Almost Sorted Array:"); printArray(almostSorted); startTime = System.nanoTime(); selectionSort(almostSorted); endTime = System.nanoTime(); timeElapsed = endTime - startTime; System.out.println("\nSelection Sort on Almost Sorted Array:"); printArray(almostSorted); System.out.println("Time elapsed: " + timeElapsed + " nanoseconds."); //Try changing the size of the array by changing the value of makeAlmostSortedArray() //Does that change the results? int[] almostSorted2 = makeAlmostSortedArray(100); System.out.println("\nAlmost Sorted Array:"); printArray(almostSorted2); newstartTime = System.nanoTime(); insertionSort(almostSorted2); newendTime = System.nanoTime(); newtimeElapsed = newendTime - newstartTime; System.out.println("\nInsertion Sort on Almost Sorted Array:"); printArray(almostSorted2); System.out.println("Time elapsed: " + newtimeElapsed + " nanoseconds.\n"); checkSpeed(timeElapsed, newtimeElapsed); } public static void insertionSort(int[] array) { for(int index = 1; index < array.length; index++) { int currentIndexValue = array[index]; int sortedIndex = index - 1; while(sortedIndex > -1 && array[sortedIndex] > currentIndexValue) { array[sortedIndex + 1] = array[sortedIndex]; sortedIndex--; } array[sortedIndex + 1] = currentIndexValue; } } public static void selectionSort(int[] array) { for(int index = 0; index < array.length - 1; index++) { int minIndex = index; for(int i = index; i < array.length; i++) { if(array[i] < array[minIndex]) { minIndex = i; } } int tempValue = array[index]; array[index] = array[minIndex]; array[minIndex] = tempValue; } } public static void printArray(int[] array) { for(int elem : array) { System.out.print(elem + " "); } System.out.println(); } /** * This method returns an array in reverse order starting from the parameter number * and going to the value 0. * @param number- the length of the desired almost sorted array * @return array - returns an array length number. Index 0 is the value number, and * index array.length-1 is 0 */ public static int[] makeReverseArray(int number) { int[] array = new int[number]; int counter = number; for(int i = 0; i < number; i++) { array[i] = counter; counter--; } return array; } /** * This method returns an array that is almost sorted, but the last index * and last index-1 are switched. * @param number- the length of the desired almost sorted array * @return array - returns an array length number with index array.length - 1 * and array.length- 2 swapped. */ public static int[] makeAlmostSortedArray(int number) { int[] array = new int[number]; for(int i = 0; i < number; i++) { array[i] = i + 1; } int temp = array[array.length - 1]; array[array.length - 1] = array[array.length - 2]; array[array.length - 2] = temp; return array; } /** * This method compares the speed of Selection Sort and Insertion Sort and prints * the results depending on which Sort method is faster. * @param selectionTime- the time elapsed during the selection sort * @param insertionTime- the time elapsed during insertion sort */ public static void checkSpeed(long selectionTime, long insertionTime) { if(selectionTime > insertionTime) { System.out.println("Insertion time is faster than Selection time by " + selectionTime - insertionTime + " nanoseconds."); } else { System.out.println("Selection time is faster than Insertion time by " + insertionTime - selectionTime + " nanoseconds."); } } } |
Unit 8: 2D Array
Question | Answer |
---|---|
8.1.5 Array Practice | public class ArrayPractice { public static void main(String[] args) { int[][] array = {{5, 4, 2, 1, 0}, {523, 63, 2342, 586, 1, 6534, 0}, {10, 9, 2, 0}}; //Call the fixArray method three times on this array: fixArray(array, 0, 4, 5); fixArray(array, 1, 6, 523+6534); fixArray(array, 2, 3, 3); print(array); } //Create a method to add the correct value to the array at the correct col, row public static void fixArray(int[][] arr, int row, int col, int value) { arr[row][col] = value; } //Do not make alterations to this method! public static void print(int[][] array) { for(int[] row: array) { for(int num: row) { System.out.print(num + " "); } System.out.println(); } } } |
8.1.6 Chess Board | public class ChessBoard { public static void main(String[] args) { //Create an 8×8 2D String array called chess. String[][] chess = new String[8][8]; chess[0] = chess[7] = new String[]{“Rook”,”Knight”,”Bishop”,”Queen”,”King”,”Bishop”,”Knight”,”Rook”}; //chess[7] = {“Rook”,”Knight”,”Bishop”,”Queen”,”King”,”Bishop”,”Knight”,”Rook”}; for(int i = 1; i < 7; i += 5) for(int j = 0; j < 8; j++) chess[i][j] = “Pawn”; for(int i = 2; i <= 5; i++) for(int j = 0; j < 8; j++) chess[i][j] = “-“; //Use this method to print the chess board onto the console print(chess); } //Do not make alterations to this method! public static void print(String[][] array) { for(String[] row: array) { for(String thing: row) { System.out.print(thing + "\t"); } System.out.println(); } } } |
8.1.7 Tic Tac Toe | public class TicTacToe { private String[][] board; public TicTacToe() { board = new String[3][3]; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) board[i][j] = “-“; } public String[][] getBoard() { return board; } } |
Tic Tac Toe Tester | public class TicTacToeTester { //You don’t need to alter any of the code in this class! //This is just to test that your TicTacToe class is working correctly public static void main(String[] args) { TicTacToe board = new TicTacToe(); printBoard(board.getBoard()); } public static void printBoard(String[][] array) { for(String[] row: array) { for(String play: row) { System.out.print(play+ " "); } System.out.println(); } } } |
8.2.7 Sum | public class Sum { public static void main(String[] args) { int[][] array = {{32, 4, 14, 65, 23, 6}, {4, 2, 53, 31, 765, 34}, {64235, 23, 522, 124, 42, 64}}; System.out.println(sumRow(array, 0)); System.out.println(sumRow(array, 1)); System.out.println(sumRow(array, 2)); } public static int sumRow(int[][] array, int row) { int sum = 0; for(int i : array[row]) sum += i; return sum; } } |
8.2.8 Tic Tac Toe | public class TicTacToe { //copy over your constructor from the Tic Tac Toe Board activity in the previous lesson! private int turn; private char[][] board; public TicTacToe() { board = new char[3][3]; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) board[i][j] = ‘-‘; turn = 0; } //this method returns the current turn public int getTurn() { return turn; } /*This method prints out the board array on to the console */ public void printBoard() { System.out.println(” 0 1 2″); for(int i = 0; i < 3; i++) { System.out.print(i + ” “); for(int j = 0; j < 3; j++) { System.out.print(board[i][j] + ” “); } System.out.print(“\n”); } } //This method returns true if space row, col is a valid space public boolean pickLocation(int row, int col) { return (board[row][col] == ‘-‘); } //This method places an X or O at location row,col based on the int turn public void takeTurn(int row, int col) { char xro; if(turn % 2 == 0) { xro = ‘X’; } else { xro = ‘O’; } board[row][col] = xro; turn++; } //This method returns a boolean that returns true if a row has three X or O’s in a row public boolean checkRow() { for(int i = 0; i < 3; i++) { char ch = board[i][0]; if (ch == board[i][1] && ch == board[i][2]) return true; } return false; } //This method returns a boolean that returns true if a col has three X or O's public boolean checkCol() { for(int i = 0; i < 3; i++) { char ch = board[0][i]; if(ch == board[1][i] && ch == board[2][i]) return true; } return false; } //This method returns a boolean that returns true if either diagonal has three X or O's public boolean checkDiag() { char ch = board[0][0]; if(ch == board[1][1] && ch == board[2][2]) return true; ch = board[0][2]; if(ch == board[1][1] && ch == board[2][0]) return true; return false; } //This method returns a boolean that checks if someone has won the game public boolean checkWin() { return(checkCol() || checkRow() || checkDiag()); } } |
Tic Tac Toe Tester | public class TicTacToeTester { public static void main(String[] args) { //This is to help you test your methods. Feel free to add code at the end to check //to see if your checkWin method works! TicTacToe game = new TicTacToe(); System.out.println(“Initial Game Board:”); game.printBoard(); //Prints the first row of turns taken for(int row = 0; row < 3; row++) { if(game.pickLocation(0, row)) { game.takeTurn(0, row); } } System.out.println("\nAfter three turns:"); game.printBoard(); } } |
Unit 9: Inheritance
Question | Answer |
---|---|
9.1.6 Person | public class Person {private String name; private String birthday; public Person (String name, String birthday) { this.name = name; this.birthday = birthday; } public String getBirthday(){ return birthday; } public String getName(){ return name; } } |
Person Runner | public class PersonRunner { public static void main(String[] args) { // Start here! Person ed = new Person(“Thomas Edison”, “February 11, 1847”); Student al = new Student(“Albert Einstein”,”March 15, 1879″, 12, 5.0); System.out.println(ed.getName()); System.out.println(ed.getBirthday()); System.out.println(al.getName()); System.out.println(al.getBirthday()); System.out.println(al.getGrade()); System.out.println(al.getGpa()); } } |
Student | public class Student extends Person {private int grade; private double gpa; public Student(String name, String birthday, int grade, double gpa){ super(name, birthday); this.grade = grade; this.gpa = gpa; } public int getGrade(){ return grade; } public double getGpa(){ return gpa; } } |
9.1.7 Book | public class Book { private int pages; private String name; public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Book Tester | public class BookTester { public static void main(String[] args) { Fiction hungerGames = new Fiction(); hungerGames.setPages(374); hungerGames.setName("The Hunger Games"); hungerGames.setAuthor("Suzanne Collins"); Dict websters = new Dict(); websters.setPages(720); websters.setName("Webster's Dictionary"); websters.setWords(171476); System.out.println(hungerGames.getName()); System.out.println(websters.getName()); } } |
Dict | public class Dict extends Book { private int words; public int getWords() { return words; } public void setWords(int words) { this.words = words; } } |
Fiction | public class Fiction extends Book { private String author; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } } |
9.1.8 Computer | public class Computer { private int screenSize; private int memory; public int getScreenSize() { return screenSize; } public void setScreenSize(int newSize) { screenSize = newSize; } public int getMemory() { return memory; } public void setMemory(int newMemory) { memory = newMemory; } } |
Computer Tester | public class ComputerTester { public static void main(String[] args) { Laptop macBook = new Laptop(); macBook.setBatteryLife(8.5); Desktop dell = new Desktop(); dell.setScreenSize(18); Computer surface = new Computer(); surface.setScreenSize(11); System.out.println(macBook.getBatteryLife()); System.out.println(dell.getScreenSize()); System.out.println(surface.getScreenSize()); } } |
Desktop | public class Desktop extends Computer { private boolean monitor; public boolean hasMonitor() { return monitor; } public void setMonitor(boolean bool) { monitor = bool; } } |
Laptop | public class Laptop extends Computer { private double batteryLife; public double getBatteryLife() { return batteryLife; } public void setBatteryLife(double newlife) { batteryLife = newlife; } } |
9.1.9 Animal | public class Animal { private String animal; public void setAnimal(String newAnimal) { animal = newAnimal; } public String getType() { return animal; } } |
Animal Tester | public class AnimalTester { public static void main(String[] args) { // Add code to test your hierarchy } } |
Dog | public class Dog extends Pet { private boolean trained; public boolean isTrained() { return trained; } public void setTrain(boolean newTrained) { trained = newTrained; } } |
Fish | public class Fish extends Pet { private String water; public String getType() { return water; } public void setWater(String newWater) { water = newWater; } } |
Pet | public class Pet extends Animal { private String name; private String size; public String getName() { return name; } public void setName(String newName) { name = newName; } public String getSize() { return size; } public void setSize(String newSize) { size = newSize; } } |
9.2.6 Student | public class Student { private String name; private int classYear; // Constructor goes here public Student(String name, int year) { this.name = name; classYear = year; } public String getName(){ return name; } public int getClassYear(){ return classYear; } public String toString(){ return name + ", class of " + classYear; } } |
Student Athlete | public class StudentAthlete extends Student { private String sport; private boolean eligible; // Add the constructor here public StudentAthlete(String name, int year, String sport, boolean eligible) { super(name, year); this.sport = sport; this.eligible = eligible; } public String getSport(){ return sport; } public boolean isEligible(){ return eligible; } @Override public String toString(){ return super.getName() + ", class of " + super.getClassYear() + ", plays " + sport; } } |
Student Tester | public class StudentTester { public static void main(String[] args) { /** * Create a student in the class of 2020 */ /** * Create a student athlete in the class of 2022 * that is eligible and plays soccer. */ // Print out both objects } } |
9.2.7 Instrument | public class Instrument { private String name; private String family; public Instrument(String name, String family) { this.name = name; this.family = family; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "" + name + " is a member of the " + family + " family."; } } |
Instrument Tester | public class InstrumentTester { public static void main(String[] args) { /** * Don’t Change This Tester Class! * * When you are finished, this should run without error. */ Wind tuba = new Wind(“Tuba”, “Brass”, false); Wind clarinet = new Wind(“Clarinet”, “Woodwind”, true); Strings violin = new Strings("Violin", true); Strings harp = new Strings("Harp", false); System.out.println(tuba); System.out.println(clarinet); System.out.println(violin); System.out.println(harp); } } |
Strings | public class Strings extends Instrument { private boolean bow; public Strings(String name, boolean bow) { super(name, “Strings”); this.bow = bow; } public boolean usesBow() { return bow; } public void setBow(boolean b) { bow = b; } } |
Wind | public class Wind extends Instrument { public boolean reed; public Wind(String name, String family, boolean reed) { super(name, family); this.reed = reed; } public void setReed(boolean r) { reed = r; } public boolean getReed() { return reed; } } |
9.2.8 Food | public class Food { private String name; private int calories; public Food (String foodName, int calories) { name = foodName; this.calories = calories; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCal() { return calories; } public void setCal(int calories) { this.calories = calories; } } |
Food Tester | public class FoodTester { public static void main(String[] args) { // Start here! System.out.println(“hi”); System.out.println(“hi”); } } |
Fruit | public class Fruit extends HealthyFood { private boolean local; private String color; public Fruit(String foodName, int calories, boolean isLocal, String foodColor) { super(foodName, calories, "Fruit"); color = foodColor; } public boolean isLocal() { return local; } public String getColor() { return color; } } |
Healthy Food | public class HealthyFood extends Food { private String group; public HealthyFood(String foodName, int calories, String foodGroup) { super(foodName, calories); group = foodGroup; } public String getGroup() { return group; } } |
9.2.9 Clothing | public class Clothing { // Your code here private String size; private String color; public Clothing(String size, String color) { this.size = size; this.color = color; } public String getSize() { return size; } public String getColor() { return color; } } |
Clothing Tester | public class ClothingTester { public static void main(String[] args) { // Start here! TShirt a = new TShirt(“L”, “red”, “denim”); Jeans b = new Jeans(“S”); Sweatshirt c = new Sweatshirt(“L”, “green”, true); Jeans d = new Jeans(“L”); System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } } |
Jeans | public class Jeans extends Clothing { public Jeans(String size) { super(size, “blue”); } } |
Sweatshirt | public class Sweatshirt extends Clothing { private boolean hood; public Sweatshirt(String size, String color, boolean hood) { super(size, color); hood = hood; } public boolean hasHood() { return hood; } } |
TShirt | public class TShirt extends Clothing { private String fabric; public TShirt(String size, String color, String fabric) { super(size, color); this.fabric = fabric; } public String getFabric() { return fabric; } } |
9.3.6 Dog | public class Dog { private String name; public Dog(String name){ this.name = name; } public String getName(){ return name; } public String speak(){ return “Bark!”; } public String toString(){ return name + ” likes to ” + speak(); } } |
Dog Tester | public class DogTester { public static void main(String[] args) { // Start here Dog a = new Dog(“a”); LoudDog b = new LoudDog(“b”); System.out.println(a + “\n” + b); } } |
Loud Dog | public class LoudDog extends Dog { public LoudDog(String name){ super(name); } // Override the speak method here public String speak(){ return “BARK!”; } //Override the toString here. //Remember, you can access the name using super.getName() public String toString(){ return super.getName() + ” is loud and likes to ” + speak(); } } |
9.3.7 Car | public class Car {//This code is complete private String model; private String mpg; public Car(String model, String mpg){ this.model = model; this.mpg = mpg; } public String getModel(){ return model; } public String getMPG(){ return mpg; } public String toString(){ return model + " gets " + mpg + " mpg."; } } |
Car Tester | public class CarTester { public static void main(String[] args) { // Create a Car object Car a = new Car(“A”, “Twelve”); // Print out the model System.out.println(a.getModel()); // Print out the MPG System.out.println(a.getMPG()); // Print the object System.out.println(a); // Create an ElectricCar object Car b = new ElectricCar(“B”); // Print out the model System.out.println(b.getModel()); // Print out the MPG System.out.println(b.getMPG()); // Print the object System.out.println(b); } } |
Electric Car | public class ElectricCar extends Car {// Complete the constructor public ElectricCar(String model){ super(model, "a"); } // Override the getMPG here. // It should return: "Electric cars do not calculate MPG. public String getMPG() { return "Electric cars do not calculate MPG."; } // Override the toString() here. // (model) is an electric car. public String toString() { return "" + super.getModel() + " is an electric car."; } } |
9.3.8 Company | public class Company { private String name; private String streetAddress; private String city; private String state; // Set missing values to null public Company(String name){ this.name = name; streetAddress = null; city = null; state = null; } public Company(String name, String streetAddress, String city, String state){ this.name = name; this.streetAddress = streetAddress; this.city = city; this.state = state; } public String getName(){ return name; } /** * Example output: * 123 Main St * Springfield, OH */ public String address(){ String rethis = “”; rethis += streetAddress + “\n”; rethis += city + “, ” + state; return rethis; } /** * Example output: * Widget Company * 123 Main St * Springfield, OH */ public String toString(){ String rethis = “”; rethis += name + “\n”; rethis += address(); return rethis; } } |
Company Tester | public class CompanyTester { public static void main(String[] args) { Company a = new Company(“a”, “b”, “c”, “d”); OnlineCompany b = new OnlineCompany(“e”, “f”); System.out.println(a + “\n” + b); } } |
Online Company | public class OnlineCompany extends Company{private String webAddress; public OnlineCompany(String name, String webAddress){ super(name); this.webAddress = webAddress; } //Return the website address public String address(){ return webAddress; } /** * Remember To get name from superclass, use super.getName() * * Example Output: * CodeHS * www.codehs.com */ public String toString(){ String rethis = ""; rethis += super.getName() + "\n"; rethis += address(); return rethis; } } |
Related Test Answers: CodeHS Python Answers