package edu.tests.model;
/**
* TestResult represents the grade on a test for one student.
*
* #author
* #version
*/
public class TestResult {
private String id;
private int grade;
/**
* Creates a new instance of TestResult with the specified
* ID of the student who took the test and the grade the
* student earned.
*
* #requires id != null && id.length() > 0 && grade >= 0
* #ensures getId().equals(id) && getGrade() == grade
*
* #param id the student's ID
* #param grade the student's grade on the test
*/
public TestResult(String id, int grade) {
this.id = id;
this.grade = grade;
}
/**
* Returns the ID of the student.
*
* #requires nothing
*
* #return the student's ID
*/
public String getId() {
return this.id;
}
/**
* Returns the grade earned by the student.
*
* #requires nothing
*
* #return the student's test grade
*/
public int getGrade() {
return this.grade;
}
/**
* Returns true if the specified object is a TestResult instance
* with the same student ID, and false otherwise.
*
* #requires nothing
*
* #return true iff someObject is a TestResult with the same student ID
*/
#Override
public boolean equals(Object someObject) {
if (this == someObject) {
return true;
}
if (someObject == null) {
return false;
}
if (this.getClass() != someObject.getClass()) {
return false;
}
TestResult aTestResult = (TestResult) someObject;
return this.getId().equals(aTestResult.getId());
}
}
package edu.westga.tests.model;
import java.util.ArrayList;
/**
* Gradebook represents the test results for all students who took a test.
*
* #author
* #version
*/
public class Gradebook {
// TODO #1: declare an instance variable called results, which is an
// ArrayList of TestResult objects
ArrayList<TestResult> results;
/**
* Creates a new Gradebook object with no test results.
*
* #requires nothing
* #ensures size() = 0
*/
// TODO#2: implement a constructor with 0 parameters that
// initializes the instance variable as an empty ArrayList
public Gradebook() {
this.results = new ArrayList<TestResult>();
}
/**
* Returns the number of test results that have been added to this
* Gradebook.
*
* #requires nothing
*
* #return how many test results this Gradebook records
*/
// TODO#3: implement the method size, which returns an int and takes
// 0 parameter
public int size() {
return this.results.size();
}
/**
* Adds the specified test result to this Gradebook.
*
* #requires aResult != null && !contains(aResult)
* #ensures size() == size()#prev + 1 && contains(aResult)
*
* #param aResult
* the test result to add to this Gradebook
*/
// TODO#4: implement the method add, with 1 parameter called aResult of type
// TestResult
// Please read the comments for the method to understand what it does
public int add(TestResult aResult) {
return this.add(aResult);
}
/**
* Returns true if a TestResult with the same ID as the specifed test result
* has previously been added to this Gradebook, and false otherwise.
*
* #requires aResult != null
*
* #return true iff the aResult has the same ID as a TestResult that has
* already been added
*
* #param aResult
* the test result to check
*/
// TODO#5: implement the method contains, which returns a boolean
// and takes 1 parameter of type TestResult
public boolean contains(TestResult aResult) {
return this.contains(aResult);
}
/**
* Returns the average grade of the test results that have been added to
* this Gradebook, or 0 if none have been added.
*
* #requires nothing
*
* #return the mean grade
*/
// TODO#6: implement method averageGrade, which returns an int
// and takes 0 parameters
public int averageGrade() {
for (int i = 0; i < results.size(); i++);
{
TestResult theResult = results.get(i);
int averageGrade = theResult.getGrade();
}
}
}
Hey everyone, I am trying to write a for-each loop which will return the average grade of the test results that have been added to the grade book. I am new to writing these loops so bear with me, but I am getting a compile error on the results.get when I put the i in the brackets of the get method. I was thinking that I had it right, I obviously do not, so any help is greatly appreciated. Thanks in advance,
you have
for (int i = 0; i < results.size(); i++);
{
TestResult theResult = results.get(i);
int averageGrade = theResult.getGrade();
}
You can't have a semicolon after the for loop, and you need to return an int... so you most likely need need
int averageGrade;
for (int i = 0; i < results.size(); i++)
{
TestResult theResult = results.get(i);
averageGrade = theResult.getGrade();
}
return averageGrade;
They way to have it, Java thinks the For loop is on it's own. Then it sees these random braces and is very confused about why they are there, hence a compile time error. It also thinks your going to return an int, and you don't so it gets confused again.
First, I doubt your code compiles since your averageGrade() method does not return anything...
Try this one:
public int averageGrade() {
int totalGrade=0;
int i = 0;
for (; i < results.size(); i++);
{
TestResult theResult = results.get(i);
totalGrade += theResult.getGrade();
}
if (i>0)
return totalGrade/i;
else return 0;
}
Related
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
I am not able to print out the info of the candy bar. Whenever I try to use the method I get an error: cannot find symbol-method printINFO.
I have tried using n.printInfo() and system.out.println(n.printinfo()), but still it doesnt work. What can I do?
Method class:
public class CandyBar
{
public enum Color
{
BLUE, BROWN, GOLD, GREEN, ORANGE,
PURPLE, RED, SILVER, WHITE, YELLOW
}
// instance variables
private String name;
private double weight;
private Color wrapper;
/**
* Constructor for objects of class CandyBar
*/
public CandyBar(String n, Color c, double w)
{
this.name = n;
this.weight = w;
this.wrapper = c;
}
public String getName()
{
return this.name;
}
public double getWeight()
{
return this.weight;
}
public Color getWrapperColor()
{
return this.wrapper;
}
public void printInfo()
{
System.out.println(this.name);
System.out.printf("%.1f oz with a ", this.weight);
System.out.println(this.wrapper + " wrapper");
}
}
Main class:
import java.util.ArrayList;
public class Lab16
{
public static void main(String[] args)
{
ArrayList<CandyBar> bars = new ArrayList<CandyBar>();
addCandyBarsToList(bars);
/**
* Use the methods you wrote below to answer all of
* the following questions.
*/
/**
* Part A:
*/
/**
* Is Twix in the list?
* If so, print all information about it.
* If not, print a message to the user.
*/
/**
* Is Mounds in the list?
* If so, print all information about it.
* If not, print a message to the user.
*/
/**
* Part B:
*/
/**
* Print all the names of candy bars with yellow wrappers.
*/
/**
* Part C:
*/
/**
* Count how many candy bars are 1.75 oz or more.
*/
/**
* Part D:
*/
/**
* Is there a candy bar that is 1.86 oz?
* If so, print the information.
* If not, print a message to the user.
* Write a binary search method to get the answer.
*/
}
/**
* This method searches a list to find a candy bar by name.
*
* #param list the list to search
* #param n a name to find
* #return the index of the candy bar
*/
public static int findCandyBar(ArrayList<CandyBar> list, String n)
{
for(int i = 0; i < list.size(); i++){
if(list.get(i).getName() == n){
return n.printInfo(i);
}else{
System.out.println("The list doesnt have that Candy");
}
}
return 1;
}
/**
* This method prints the names of the candy bars that have a certain
* wrapper color.
*
* #param list the list to search
* #param c the color wrapper to find
*/
public static void findByColor(ArrayList<CandyBar> list, CandyBar.Color c)
{
}
/**
* This method counts the number of candy bars that weigh greater than
* or equal to the weight input parameter.
*
* #param list the list to search
* #param w the weight to compare to
* #return the count of candy bars
*/
public static int countByWeight(ArrayList<CandyBar> list, double weight)
{
return 0;
}
/**
* This method searches a list using binary search.
*
* #param list the list to search
* #param first the first index
* #param last the last index
* #param w the value to search for
* #return the index of the candy bar
*/
public static int binaryFind(ArrayList<CandyBar> list, int first, int last, double w)
{
return -1;
}
/**
* This method adds candy bars to a list.
*
* #param list the list to add to
*/
public static void addCandyBarsToList(ArrayList<CandyBar> list)
{
CandyBar kitkat = new CandyBar("KitKat", CandyBar.Color.RED, 1.5);
list.add(kitkat);
CandyBar grand = new CandyBar("One-hundred Grand", CandyBar.Color.RED, 1.5);
list.add(grand);
CandyBar crunch = new CandyBar("Crunch", CandyBar.Color.BLUE, 1.55);
list.add(crunch);
CandyBar hershey = new CandyBar("Hershey", CandyBar.Color.BROWN, 1.55);
list.add(hershey);
CandyBar krackel = new CandyBar("Krackel", CandyBar.Color.RED, 1.55);
list.add(krackel);
CandyBar caramello = new CandyBar("Caramello", CandyBar.Color.PURPLE, 1.6);
list.add(caramello);
CandyBar what = new CandyBar("Whatchamacallit", CandyBar.Color.YELLOW, 1.6);
list.add(what);
CandyBar almond = new CandyBar("Almond Joy", CandyBar.Color.BLUE, 1.61);
list.add(almond);
CandyBar goodbar = new CandyBar("Mr. Goodbar", CandyBar.Color.YELLOW, 1.75);
list.add(goodbar);
CandyBar twix = new CandyBar("Twix", CandyBar.Color.GOLD, 1.79);
list.add(twix);
CandyBar henry = new CandyBar("Oh Henry", CandyBar.Color.YELLOW, 1.8);
list.add(henry);
CandyBar milkyWay = new CandyBar("Milky Way", CandyBar.Color.GREEN, 1.84);
list.add(milkyWay);
CandyBar payDay = new CandyBar("PayDay", CandyBar.Color.ORANGE, 1.85);
list.add(payDay);
CandyBar snickers = new CandyBar("Snickers", CandyBar.Color.BLUE, 1.86);
list.add(snickers);
CandyBar butterfinger = new CandyBar("Butterfinger", CandyBar.Color.YELLOW, 1.9);
list.add(butterfinger);
CandyBar musketeers = new CandyBar("Three Musketeers", CandyBar.Color.SILVER, 1.92);
list.add(musketeers);
CandyBar reeses = new CandyBar("Reese's FastBreak", CandyBar.Color.ORANGE, 2);
list.add(reeses);
CandyBar babyRuth = new CandyBar("Baby Ruth", CandyBar.Color.SILVER, 2.1);
list.add(babyRuth);
}
}
The printInfo() method is declared on the CandyBar object, but here you are trying to call printInfo() on a String object. This method does not exist on String.
/**
* This method searches a list to find a candy bar by name.
*
* #param list the list to search
* #param n a name to find
* #return the index of the candy bar
*/
public static int findCandyBar(ArrayList<CandyBar> list, String n)
{
for(int i = 0; i < list.size(); i++){
if(list.get(i).getName() == n){
return n.printInfo(i); <-- calling n.printInfo(i) will not work as printInfo() does not exist on String
You instead need to pay attention to the method signature of printInfo():
It exists on CandyBar, not on String.
It does not accept any parameter arguments.
It is a void method, i.e. does not return an object.
So instead of:
return n.printInfo(i);
Use this:
i.printInfo();
I am having trouble with using methods from other classes. I will post specific code below:
import java.util.ArrayList;
/**
* Train models a train containing a car class and a seat class.
*
* #author Nicholas Howes, Carleton University
* #version Oct 9th, 2017
*/
public class Train
{
/** The cars in this train. */
private ArrayList<Car> cars;
/**
* Constructs an empty train; i.e., one that has no cars.
*/
public Train()
{
cars = new ArrayList<Car>(0);
}
/**
* Adds the specified car to this train.
* #param car The car object being appended to the end of the list.
*/
public void addCar(Car car)
{
cars.add(car);
}
/**
* Returns this trains's list of cars. This method is intended for
* testing purposes only, and should not be called by other objects,
* as it may be removed from the final version of this class.
*
* #return A list of the cars in the train
*/
public ArrayList<Car> cars()
{
return cars;
}
/**
* Attempts to issue a ticket for a business class seat or an
* economy class seat, as specified by the method's argument.
* It will attempt to book a seat in the first car of the appropriate
* type, but if a seat is not available it will attempt to book a seat
* in the second car of the appropriate type, and so on.
* A request to issue a ticket in a business-class car will never result
* in a seat being reserved in an economy-class car, and vice-versa.
* Returns true if successful, false otherwise.
*/
public boolean issueTicket(boolean businessClassSeat)
{
for(int i = 0; i < cars.size(); i++) {
if(businessClassSeat == (isBusinessClass())) {
cars(i).bookNextSeat();
if(bookNextSeat == true) {
i = cars.size();
return true;
}
}
}
return false;
}
/**
* Cancels the ticket for the specified seat in the specified car.
* Returns true if successful, false otherwise.
*/
public boolean cancelTicket(int carId, int seatNo)
{
return false;
}
}
/**
* Car models a car in a passenger train.
*
* #author Nicholas Howes, Carleton University
* #version 1.0 September 29, 2017
*/
public class Car
{
/** This car's identifier. */
private int id;
/**
* true == this car is a business-class car,
* false == this car is an economy-class car.
*/
private boolean businessClass;
/** The cost of a business class seat, in dollars. */
public static final double BUSINESS_SEAT_COST = 125.0;
/** The cost of an economy class seat, in dollars. */
public static final double ECONOMY_SEAT_COST = 50.0;
/** The number of seats in a business class car. */
public static final int BUSINESS_SEATS = 30;
/** The number of seats in an economy class car. */
public static final int ECONOMY_SEATS = 40;
/** The list of this car's seats. */
private Seat[] seats;
/**
* Constructs a new Car object with the specified id.
* If parameter isBusinessClass is true, the car is a business-class
* car. If parameter isBusinessClass is false, the car is an
* economy-class car.
* #param carId The car id # for the new car object.
* #param isBusinessClass The boolean value corresponding to the class
* of the car.
*/
public Car(int carId, boolean isBusinessClass)
{
id = carId;
businessClass = isBusinessClass;
int Count = 1;
if (businessClass == true) {
seats = new Seat[BUSINESS_SEATS];
for(int i = 0; i < seats.length; i++) {
seats[i] = new Seat(Count, BUSINESS_SEAT_COST);
Count++;
}
} else {
seats = new Seat[ECONOMY_SEATS];
for(int i = 0; i < seats.length; i++) {
seats[i] = new Seat(Count, ECONOMY_SEAT_COST);
Count++;
}
}
}
/**
* Returns this car's list of seats. This method is intended for
* testing purposes only, and should not be called by other objects,
* as it may be removed from the final version of this class.
*
* #return The seats in this car, an array of Seat objects.
*/
public Seat[] seats()
{
return seats;
}
/**
* Returns true if this is a business-class car,
* false if this is an economy-class car.
* #return true The boolean value returned if the car is business class.
* #return false The boolean value returned if the car is economy class.
*/
public boolean isBusinessClass()
{
if(businessClass == true) {
return true;
}
return false;
}
/**
* Returns the id of this car.
* #return id The value returned is the id # of the car.
*/
public int id()
{
return id;
}
/**
* This method is called when the specified seat has been booked,
* to print a ticket for that seat.
*
* #param seatNo The integer identifier of the seat.
*/
private void printTicket(int seatNo)
{
System.out.println("Car ID: " + id);
System.out.println("Seat number: " + seatNo);
System.out.println("Price: ");
if (businessClass) {
System.out.println(BUSINESS_SEAT_COST);
} else {
System.out.println(ECONOMY_SEAT_COST);
}
}
/**
* Attempts to book a seat. If successful, this method prints a
* ticket and returns true.
* If no seats are available, this method returns false.
* #return true The return value when a new seat is booked.
* #return false The return value when no seats are available.
*/
public boolean bookNextSeat()
{
// After booking an available seat, print the ticket by calling
// private method printTicket(); e.g.,
// printTicket(seats[i].number());
for(int i = 0; i < seats.length; i++) {
if(seats[i].isBooked() == false) {
seats[i].book();
printTicket(seats[i].number());
return true;
}
}
return false;
}
/**
* Cancels the booking for the specified seat, which must be between
* 1 and the maximum number of seats in the car.
* If the seat number is valid and if the seat has been reserved, this
* method cancels the booking for that seat and returns true.
* If the seat number is not valid, this method returns false.
* If the seat number is valid, but the seat has not been reserved,
* this method returns false.
* #param seatNo The seat number to cancel if it is booked and valid.
*/
public boolean cancelSeat(int seatNo)
{
if(seatNo < 1 || seatNo > seats.length) {
return false;
}
if(seats[seatNo-1].isBooked() == false) {
return false;
}
seats[seatNo-1].cancelBooking();
return true;
}
}
/**
* Seat models a seat in a car in a passeger train.
*
* #author D.L. Bailey, SCE
* #version 1.00 January 28, 2007
*/
public class Seat
{
private int number; // the seat's number
private boolean booked; // has this seat has been reserved?
private double price; // the cost of a ticket for this seat, in dollars
/**
* Constructs a new Seat with the specified seat number and
* ticket price.
*/
public Seat(int seatNo, double cost)
{
booked = false;
number = seatNo;
price = cost;
}
/**
* Returns the cost of purchasing a ticket for this Seat.
*/
public double price()
{
return price;
}
/**
* Returns this seat's number.
*/
public int number()
{
return number;
}
/**
* Returns true if someone has purchased a ticket
* for this Seat.
*/
public boolean isBooked()
{
return booked;
}
/**
* If this seat is available, books it and returns true.
* If the seat is not available, returns false.
*/
public boolean book()
{
if (!booked) {
booked = true;
return true;
}
return false;
}
/**
* If this seat is booked, cancels the booking and returns true.
* If the seat was not booked, returns false.
*/
public boolean cancelBooking()
{
if (booked) {
booked = false;
return true;
}
return false;
}
}
The problem I am having is with the method boolean issueTicket in class Train. I understand I can use the methods from my Car class to search all cars of the specified type (the parameter passed in issueTicket) either being business or economy (true or false) and then using the method bookNextSeat to book the next empty seat then exit the for loop if it returns true by setting i equal to the arraylist size. What am I doing wrong with all of these method uses from class car?
First of all, statement i = cars.size(); is required at all, you can use break; instead to break out of the loop. I would suggest take a method scope variable boolean status = false and update value of status only when bookNext returns true and call break and return the status variable instead of hardcoded true false.
Since return statement is only within the scope of loop method won’t be able to return anything, in fact you will get missing return statement error.
It seems that 20 regiments were in a continuous process of formation. The first had 1000 men, the second had 950, the third 900, and so on down to the twentieth regiment, which garrisoned only 50. During each week, 100 men were added to each regiment, and at week's end, the largest regiment was sent off to the front.This lasted for a total of 20 weeks.
For this program I have already managed to print out the original number of men for each regiment. But I am having difficult adding 100 men to each regiment.The adding men must be a method in the army class. I am getting the regiment objects using a .txt file. All this files contains is the names of regiments numbered 1-20.
public class Regiment {
private String name; //name of regiment
private int regNumber; //regiment number
private int men; // regiment men
/**
* Creates a Regiment object.
*
* #param regNumber the regiment number
* #param name the name of the regiment
* #param men the number of men in a regiment
*/
public Regiment(int regNumber, String name, int men) {
this.name = name;
this.regNumber = regNumber;
this.men = men;
}
/**
* Returns the name of the regiment.
*
* #return the regiment name
*/
public String getName() {
return name;
}
/**
* Returns the number of the regiment.
*
* #return regiment number
*/
public int getregNumber() {
return regNumber;
}
/**
* Returns the number of men in a regiment.
*
* #return men in regiment
*/
public int getMen() {
return men;
}
/**
* Computes the number of men in a regiment
*/
public int addMen2(int RegNumber) {
int men = 1050 - (regNumber * 50);
return men;
}
}
class ArmyDataList {
public ArrayList<Regiment> list; // list of regiment objects
/**
* Creates an empty list
*/
public ArmyDataList() {
list = new ArrayList<Regiment>();
}
/**
* Appends a regiment object to the list.
*
* #param current the object to be appended to the list
*/
public void AddToList(Regiment current) {
list.add(current);
}
/**
* Removes a regiment object to the list.
*
* #param current the object to be removed from the list
*/
public void RemoveFromList(Regiment current) {
list.remove(current);
}
/**
* Gets the largest regiment based on men.
*/
public Regiment getLargest() {
if (list.isEmpty()) {
return null;
}
Regiment Reg1 = list.get(0);
for (int i = 1; i < list.size(); i++) {
Regiment current = list.get(i); // get next regiment
// is current regiment > largest
if (current.getMen() > Reg1.getMen()) {
Reg1 = current;
}
}
return Reg1;
}
/**
* Adds men to each regiment.
*/
public void addMen() {
}
/**
* Converts the list to a multi-line string, with each line containing the
* data for one regiment.
*
* #return the String containing all the data on the list
*/
public String toString() {
String out
= String.format("%28s%12s%n", "Regiments", " Men")
+ String.format("%12s%n", "Number")
+ String.format("%12s%16s%14s%n", "=======", "===============",
"=========");
for (int i = 0; i < list.size(); i++) {
Regiment regim = list.get(i);
int regNumber = regim.getregNumber();
String name = regim.getName();
int men = regim.addMen2(regNumber);
out = out + String.format("%12s", regNumber)
+ String.format("%16s", name)
+ String.format("%10s", men)
+ "\n";
}
return out + "\n";
}
}
public class RegimentTest {
public static void main(String[] args) throws IOException
{
ArmyDataList army = new ArmyDataList();
// create Scanner object to read each line of file until eof
Scanner fileScan = new Scanner(new File("regiments.txt"));
System.out.println("Report Summary:\n");
while (fileScan.hasNext()) // while not eof...
{
// read next line
String line = fileScan.nextLine();
// "echo print" data entered
System.out.println(line);
// 1. create a Scanner object
Scanner in = new Scanner(line) ;
// 2. extract tokens from current line
int regNumber = in.nextInt();
String name = in.next();
int men = 0 ; //men is set to 0 only because I havent add the men yet
// 3. create Regiment object passing the tokens to the constructor
Regiment adder = new Regiment(regNumber, name, men );
// 4. add object to list
army.AddToList(adder) ;
}
System.out.println(army.toString());
}
You can write addNewMen() method in Regiment Class where you can add 100 more men as men is the property of regiment.
I have a class that implements the Comparable interface. In this class I need to override compareTo method in order to sort objects by String values.
If you scroll down to the bottom I'm attempting to make my method & I need to in the main method sort an array of Courses (using the compareTo method I'm making) by first Department type and then by course number, etc. but this requires comparing 2 strings.
import java.io.Serializable;
import java.io.*;
import java.util.*;
public class Course implements Comparable<Course>, Serializable {
private String prefix;
private int number;
private String Department;
private String grade;
/**
* Constructs the course with the specified information.
*
* #param prefix the prefix of the course designation
* #param number the number of the course designation
* #param Department the Department of the course
* #param grade the grade received for the course
*/
public Course(String prefix, int number, String Department, String grade)
{
this.prefix = prefix;
this.number = number;
this.Department = Department;
if (grade == null)
this.grade = "";
else
this.grade = grade;
}
/**
* Constructs the course with the specified information, with no grade
* established.
*
* #param prefix the prefix of the course designation
* #param number the number of the course designation
* #param Department the Department of the course
*/
public Course(String prefix, int number, String Department)
{
this(prefix, number, Department, "");
}
public String getPrefix()
{
return prefix;
}
/**
* Returns the number of the course designation.
*
* #return the number of the course designation
*/
public int getNumber()
{
return number;
}
/**
* Returns the Department of this course.
*
* #return the prefix of the course
*/
public String getDepartment()
{
return Department;
}
/**
* Returns the grade for this course.
*
* #return the grade for this course
*/
public String getGrade()
{
return grade;
}
/**
* Sets the grade for this course to the one specified.
*
* #param grade the new grade for the course
*/
public void setGrade(String grade)
{
this.grade = grade;
}
/**
* Returns true if this course has been taken (if a grade has been received).
*
* #return true if this course has been taken and false otherwise
*/
public boolean taken()
{
return !grade.equals("");
}
* Determines if this course is equal to the one specified, based on the
* course designation (prefix and number).
*
* #return true if this course is equal to the parameter
*/
public boolean equals(Object other)
{
boolean result = false;
if (other instanceof Course)
{
Course otherCourse = (Course) other;
if (prefix.equals(otherCourse.getPrefix()) &&
number == otherCourse.getNumber())
result = true;
}
return result;
}
The compareTo function:
public int compareTo(Course o)
{
if(getDepartment().equals(o.getDepartment()))
{
return 0;
}
else if()
{
return -1;
}
else
{
return 1;
}
}
/**
* Creates and returns a string representation of this course.
*
* #return a string representation of the course
*/
public String toString()
{
String result = prefix + " " + number + ": " + Department;
if (!grade.equals(""))
result += " [" + grade + "]";
return result;
}
}
Main class thus far:
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import java.*;
public class StackCourse
{
public static void main(String[] args)
{
Course a = new Course("EEE", 230, "Engineering");
Course b = new Course("MAT", 150, "Liberal Arts");
Course c = new Course("PHY", 150, "Liberal Arts");
Course d = new Course("PHI", 304, "Liberal Arts");
Course e = new Course("ECN", 214, "W.P. Carey");
Course f = new Course("EEE", 120, "Engineering");
Course[] courses = {a,b,c,d,e,f};
for(int i=0; i<courses.length; i++)
System.out.println(courses[i].getDepartment());
}
}
public int compareTo(Course o)
{
if(getDepartment().compareTo(o.getDepartment()) ==0){
if(getNumber() < o.getNumber()) return -1;
else if(getNumber() > o.getNumber()) return 1;
else return 0;
}
return getDepartment().compareTo(o.getDepartment());
}
Output:
EEE 120: Engineering
EEE 230: Engineering
MAT 150: Liberal Arts
PHY 150: Liberal Arts
PHI 304: Liberal Arts
ECN 214: W.P. Carey
If I follow your question, I believe you wanted something like this
public int compareTo(Course o)
{
int a = getDepartment().compareTo(o.getDepartment());
if(a != 0)
{
return a;
}
return Integer.valueOf(getNumber()).compareTo(o.getNumber());
}
Note: You can return when the fields you are comparing aren't 0, because those fields aren't equal.
Just use String's built-in compareTo method:
#Override
public int compareTo(Course o) {
return this.Department.compareTo(o.Department);
}
I searched throughout the forums and could not find what I was looking for. I am doing an assignment for school and I need to implement some methods. I did most of them and am getting the output I need. However, I'm having trouble implementing the Cartesian Product (xproduct) method.
Here is my code so far:
import java.util.*;
public class Set
{
private ArrayList<String>elements;
/**
* creates an empty set
*/
public Set()
{
elements = null;
}
/**
* creates a set using the elements of the ArrayList s.
* #param s the ArrayList whose elements are used to create this set.
* #throws IllegalArgumentException if s contains duplicity.
*/
public Set(ArrayList<String> s)
{
int i;
elements = new ArrayList<String>();
for(i=0;i<s.size();i++)
{
if(elements.contains(s.get(i)))
{throw new IllegalArgumentException("Set(ArrayList<String>)duplicity not allowed in sets");}
elements.add(s.get(i));
}
}
/**
* creates a set using the elements of the array s.
* #param s the array whose elements are used to create this set.
* #throws illegalArgumentException if s contains duplicity.
*/
public Set(String[] s)
{
int i;
elements = new ArrayList<String>();
for(i=0; i<s.length; i++)
{
if (elements.contains(s[i]))
{throw new IllegalArgumentException("Set(String[]):duplicity not allowed in sets");}
elements.add(s[i]);
}
}
/**
* determines whether a set contains the specified element
* #param elt an element
* #return true if elt is an element of this set; otherwise, false
*/
public boolean isElement(String elt)
{
return elements.contains(elt);
}
/**
* determines the size of this set.
* #return the size of this set.
*/
public int cardinality()
{
return elements.size();
}
/**
* computes the intersection of this set and the
* specified set.
* #param s a set
* #return a set representing the intersection of this set
* and s.
*/
public Set intersect(Set s)
{
int i;
ArrayList<String> result = new ArrayList<String>();
for (i=0;i<s.cardinality();i++)
{
if (this.isElement(s.elements.get(i)))
{result.add(s.elements.get(i));}
}
return new Set(result);
}
/**
* computes the union of this set and the specified set.
* #param s a sets
* #return a set representing the union of this set
* and s.
*/
public Set union(Set s)
{
int i;
ArrayList<String> result = new ArrayList<String>();
result.addAll(this.elements);
result.addAll(s.elements);
for(i=0;i<s.cardinality();i++)
{
if (this.isElement(s.elements.get(i)))
{result.remove(s.elements.get(i));}
}
return new Set(result);
}
/**
* computes the difference between this set and the
* specified set.
* #param s a set
* #return a set representing the difference between
* this set and s.
*/
public Set diff(Set s)
{
int i;
ArrayList<String> result = new ArrayList<String>();
result.addAll(this.elements);
for(i=0;i<s.cardinality();i++)
{
if (this.isElement(s.elements.get(i)))
{result.remove(s.elements.get(i));}
}
return new Set(result);
}
/**
* computes the symmetric difference between this set
* and the specified set.
* #param s a set
* #return a set representing the symmetrical difference
* between this set and s.
*/
public Set symDiff(Set s)
{
int i;
ArrayList<String> result = new ArrayList<String>();
result.addAll(this.elements);
result.addAll(s.elements);
for(i=0;i<s.cardinality();i++)
{
if (this.isElement(s.elements.get(i)) && s.isElement(this.elements.get(i)))
{result.remove(this.elements.get(i));
result.remove(s.elements.get(i));}
}
return new Set(result);
}
/**
* computes the Cartesian product for this set
* and the specified set.
* #param s a set
* #return a set representing the Cartesian product
* of this set and s.
*/
public Set xProduct(Set s)
{
int i;
ArrayList<String> result = new ArrayList<String>();
result.addAll(this.elements);
result.addAll(s.elements);
}
/**
* determines whether a set is empty
* #return true if this set is empty; otherwise, false
*/
public boolean isEmpty()
{
return elements.isEmpty();
}
/**
* determines whether this set is equal to the specified
* set.
* #param s a set
* #return true if this set is equal to s; otherwise, false
*/
public boolean equals(Set s)
{
return elements.equals(s.elements);
}
/**
* determines whether this set is a subset of the specified set.
* #param s a set
* #return true if this set is a subset of s; otherwise, false
*/
public boolean subset(Set s)
{
return elements.containsAll(s.elements);
}
/**
* determines whether this set is a proper subset of the specified set.
* #param s a set
* #return true if this set is a proper subset of s; otherwise, false
*/
public boolean properSubset(Set s)
{
if(elements.equals(s.elements) && elements.containsAll(s.elements))
{return false;}
else{
return true;
}
}
/**
* returns a string {x1,x2,...,xn} representing this set,
* where x1,x2,...,xn are elements of this set.
* #return a string representation of this set formatted
* as specified.
*/
#Override
public String toString()
{
return "{"+this.elements+"}";
}
public static void main(String[] args)
{
String[]a1 = {"2","4","6","8"};
String[]a2 = {"2","3","5","7"};
String[]a3 = {"1","3","5"};
Set s1 = new Set(a1);
Set s2 = new Set(a2);
Set s3 = new Set(a3);
System.out.print("S1 ="); System.out.printf("%s",s1);
System.out.println();
System.out.print("S2 ="); System.out.printf("%s",s2);
System.out.println();
System.out.print("S3 ="); System.out.printf("%s",s3);
System.out.println();System.out.println();
System.out.println("(S1 \u222A S2:)");
System.out.printf("%s \u222A %s = %s%n",s1,s2,s1.union(s2));
System.out.println();
System.out.println("(S1 \u2296 S2) \u222a (S1 \u2229 S2) \u222a (S2 \u2296 S1)");
System.out.printf("%s \u2296 %s \u222a %s \u2229 %s \u222a %s \u2296 %s = %s%n",s1,s2,s1,s2,s2,s1,s1.diff(s2).union(s1.intersect(s2).union(s2.diff(s1))));
//Cartesian Product of s1 and s2
//Cartesian product of s2 and s1
}
}
Any guidance would be appreciated.
I do not understand why you have diffculties, but the cartezian product of Set1 x Set2 could be computed something like this:
Product = {}
Set1. iterate with i
Set2.iterate with j
Product.append (pair(i,j))
If you still have difficulties, please tell me to code it in Java. For now I posted only the pseudocode.