cannot find symbol method printinfo? [duplicate] - java

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();

Related

How to set up a basic test method for a java program using junit?

I have a project that is a hardware store consisting of methods that save, search, and edit data. The data is the items stored in a txt database. I have to create a JUNIT test case that tests the methods of the hardware store class. There are three classes in total: hardwarestore, mainapp, and item. But the only one that needs to be tested is hardwarestore. And the only methods that don't need to be tested are the readDatabase() and the writeDatabase().
For my JUNIT classes I have hardwarestoretest that I will implement with test methods for the hardwarestore class. I also have a testrunner class that runs the test methods in hardwarestoretest. The test methods will compose of assertion tests.
Assertions
I am fairly new with JUNIT testing and need just some help getting started. I wrote part of the test classes but they fail when ran. The output I get says that there are no runnable tests even though I tried to implement a test method for addNewItem.
Here is my code for hardwarestore in a hardwarestore package
Item.java
package hardwarestore;
/**
* This class is a very simple representation of a hardware item. There are only getter
* methods and no setter methods and as a result an item cannot be mutated once
* initialized. An item object can also call the two override methods
* <CODE>toString()</CODE> and <CODE>equals()</CODE>
*
* #author Junye Wen
*/
public class Item {
private final String idNumber;
private final String name;
private final String category;
private int quantity;
private final float price;
/**
* This constructor initializes the item object. The constructor provides no
* user input validation. That should be handled by the class that creates a
* item object.
*
* #param idNumber a <b><CODE>String</CODE></b> that represents the ID
* random string of length 5 – can contain letters and numbers
*
* #param name a <b><CODE>String</CODE></b> that represents the name.
*
* #param category a <b><CODE>String</CODE></b> that represents the category.
* Door&Window, Cabinet& Furniture, Fasteners, Structural, Other.
*
* #param quantity a <b><CODE>int</CODE></b> that represents the quantity
*
* #param price an <b><CODE>float</CODE></b> that represents the price
*
*/
public Item(String idNumber, String name, String category, int quantity, float price) {
this.idNumber = idNumber;
this.name = name;
this.category = category;
this.quantity = quantity;
this.price = price;
}
/**
* This method returns the item's tracking number.
*
* #return a <b><CODE>String</CODE></b> that is the ID number of the item.
*/
public String getIdNumber() {
return idNumber;
}
/**
* This method returns the item's name.
*
* #return a <b><CODE>String</CODE></b> that is the item's name.
*/
public String getName() {
return name;
}
/**
* This method returns the item's category.
*
* #return a <b><CODE>String</CODE></b> that is the item's category.
*/
public String getCategory() {
return category;
}
/**
* This method returns the item's quantity.
*
* #return an <b><CODE>int</CODE></b> that is the item's weight
*/
public int getQuantity() {
return quantity;
}
/**
* This method set the item's quantity.
*
* #param quantity a <b><CODE>int</CODE></b> that represents the quantity
*/
public void setQuantity(int quantity) {
this.quantity= quantity;
}
/**
* This method returns the item's price.
*
* #return a <b><CODE>float</CODE></b> that is the item's price
*/
public float getPrice() {
return price;
}
/**
* This method returns the item's fields as a string representation.
*
* #return a <b><CODE>String</CODE></b> that lists the fields of the item
* object delineated by a space and in the same order as the constructor
*/
#Override
public String toString() {
return idNumber + "~" + name + "~" + category + "~" + quantity + "~"
+ String.format("%.2f", price) + "\n";
}
/**
* This method provides a way to compare two item objects.
*
* #param c a <b><CODE>Item</CODE></b> object that is used to compare to
* <b><CODE>this</CODE></b> item. Two orders are equal if their ID is the
* same.
* #return the <CODE>boolean</CODE> value of the comparison.
*/
public boolean equals(Item c) {
return c.getIdNumber().equals(this.idNumber);
}
}
HardwareStore.java
package hardwarestore;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This class is used to represent a database interface for a list of
* <CODE>item</CODE>'s. It using a plain-text file "database.txt" to store and
* write item objects in readable text form. It contains an
* <CODE>ArrayList</CODE> called <CODE>itemList</CODE> to store the database in
* a runtime friendly data structure. The <CODE>itemList</CODE> is written to
* "database.txt" at the end of the <CODE>HardwareStore</CODE> object's life by
* calling <CODE>writeDatabase()</CODE>. This class also provides methods for
* adding, removing, and searching for items in the list.
*
* #author Junye Wen
*/
public class HardwareStore {
private ArrayList<Item> itemList;
private static final String DATA_FILE_NAME = "database.txt";
/**
* This constructor creates an empty ArrayList and then calls the
* <CODE>readDatabase()</CODE> method to populate items previously stored.
*
* #throws IOException
*/
public HardwareStore() throws IOException {
itemList = new ArrayList<>();
readDatabase();
}
/**
* Method getAllItemsFormatted returns the current list of items in the Arraylist in
* no particular order.
*
* #return a formatted String representation of all the items in itemList.
*/
public String getAllItemsFormatted() {
return getFormattedItemList(itemList);
}
/**
* Private method getFormattedPackageList used as an auxiliary method to return a given ArrayList
* of items in a formatted manner.
*
* #param items the item list to be displayed.
* #return a formatted String representation of all the items in the list give as a parameter.
*/
private String getFormattedItemList(ArrayList<Item> items) {
String text = " ------------------------------------------------------------------------------------\n" +
String.format("| %-10s| %-25s| %-20s| %-10s| %-10s|%n", "ID Number", "Name", "Category", "Quantity", "Price") +
" ------------------------------------------------------------------------------------\n";
for (int i = 0; i < items.size(); i++) {
text += String.format("| %-10s| %-25s| %-20s| %-10s| %-10s|%n",
items.get(i).getIdNumber(),
items.get(i).getName(),
items.get(i).getCategory(),
Integer.toString(items.get(i).getQuantity()),
String.format("%.2f", items.get(i).getPrice()));
}
text += " ------------------------------------------------------------------------------------\n";
return text;
}
/**
* This method is used to add a item to the itemList ArrayList.
*
* #param idNumber a <CODE>String</CODE> representing the ID number of item
* #param name a <CODE>String</CODE> representing the name of item
* #param category a <CODE>String</CODE> representing the category of item
* #param quantiy an <CODE>int</CODE> representing the quantiy of item
* #param price a <CODE>float</CODE> representing the price of item
*/
public void addNewItem(String idNumber, String name, String category, int quantiy, float price) {
//If passed all the checks, add the item to the list
itemList.add(new Item(idNumber, name, category, quantiy, price));
System.out.println("Item has been added.\n");
}
/**
* Add a certain quantity of the given item index.
* Preconditions: 1. Item exists.
* #param itemIndex the index of the item in the itemList
* #param quantity the quantity to remove
*/
public void addQuantity(int itemIndex, int quantity) {
Item temp = getItem(itemIndex);
temp.setQuantity(temp.getQuantity() + quantity);
System.out.println("Quantity updated.\n");
}
/**
* Removes a certain quantity of the given item index.
* Preconditions: 1. Item exists. 2. Quantity to remove smaller than current quantity.
* #param itemIndex the index of the item in the itemList
* #param quantity the quantity to remove
*/
public void removeQuantity(int itemIndex, int quantity) {
Item temp = getItem(itemIndex);
temp.setQuantity(temp.getQuantity() - quantity);
System.out.println("Quantity updated.\n");
}
/**
* Returns all the items that (partially) match the given name.
* #param name the name to match.
* #return a string containing a table of the matching items.
*/
public String getMatchingItemsByName(String name) {
ArrayList<Item> temp = new ArrayList<Item>();
for (Item tempItem : itemList) {
if (tempItem.getName().toLowerCase().contains(name.toLowerCase())) {
temp.add(tempItem);
}
}
if (temp.size() == 0) {
return null;
} else {
return getFormattedItemList(temp);
}
}
/**
* Returns all the items with current quantity lower than (or equal) the
* given threshold.
* #param quantity the quantity threshold.
* #return a string containing a table of the matching items.
*/
public String getMatchingItemsByQuantity(int quantity) {
ArrayList<Item> temp = new ArrayList<Item>();
for (Item tempItem : itemList) {
if (tempItem.getQuantity() <= quantity) {
temp.add(tempItem);
}
}
if (temp.isEmpty()) {
return null;
} else {
return getFormattedItemList(temp);
}
}
/**
* This method can be used to find a item in the Arraylist of items.
*
* #param idNumber a <CODE>String</CODE> that represents the ID number of
* the item that to be searched for.
* #return the <CODE>int</CODE> index of the items in the Arraylist of
* items, or -1 if the search failed.
*/
public int findItem(String idNumber) {
int index = -1;
for (int i = 0; i < itemList.size(); i++) {
String temp = itemList.get(i).getIdNumber();
if (idNumber.equalsIgnoreCase(temp)) {
index = i;
break;
}
}
return index;
}
/**
* This method is used to retrieve the Item object from the
* <CODE>itemList</CODE> at a given index.
*
* #param i the index of the desired <CODE>Item</CODE> object.
* #return the <CODE>Item</CODE> object at the index or null if the index is
* invalid.
*/
public Item getItem(int i) {
if (i < itemList.size() && i >= 0) {
return itemList.get(i);
} else {
System.out.println("Invalid Index.\n");
return null;
}
}
/**
* This method opens the database file and overwrites it with a
* text representation of all the items in the <CODE>itemList</CODE>. This
* should be the last method to be called before exiting the program.
*
* #throws IOException
*/
public void writeDatabase() throws IOException {
PrintWriter pw = new PrintWriter(DATA_FILE_NAME);
for (Item c : itemList) {
pw.print(c.toString());
}
pw.close();
}
/**
* The method opens the database file and initializes the <CODE>itemList</CODE>
* with its contents. If no such file exists, then one is created.
* The contents of the file are "loaded" into the itemList ArrayList in no
* particular order. The file is then closed during the duration of the
* program until <CODE>writeDatabase()</CODE> is called.
*
* #throws IOException
*/
public void readDatabase() throws IOException {
File dataFile = new File(DATA_FILE_NAME);
// If data file does not exist, create it.
if (!dataFile.exists()) {
System.out.println("database.txt does not exist, creating one now . . .");
//if the file doesn't exists, create it
PrintWriter pw = new PrintWriter(DATA_FILE_NAME);
//close newly created file so we can reopen it
pw.close();
return; // No need to try to read anything from an empty file, so return.
}
Scanner itemScanner = new Scanner(new FileReader(dataFile));
//Initialize the Array List with items from database.txt
while (itemScanner.hasNextLine()) {
// split values using the space character as separator
String[] temp = itemScanner.nextLine().split("~");
itemList.add(new Item(temp[0], temp[1], temp[2],
Integer.parseInt(temp[3]), Float.parseFloat(temp[4])));
}
//item list is now in the ArrayList completely so we can close the file
itemScanner.close();
}
}
MainApp.java
package hardwarestore;
import java.io.IOException;
import java.util.Scanner;
/**
* This is the main class of the Hardware Store database manager. It provides a
* console for a user to use the 5 main commands.
*
* #author Junye Wen
*/
public class MainApp {
// This object will allow us to interact with the methods of the class HardwareStore
private final HardwareStore hardwareStore;
private static final Scanner CONSOLE_INPUT = new Scanner(System.in); // Used to read from System's standard input
/**
* Default constructor. Initializes a new object of type HardwareStore
*
* #throws IOException
*/
public MainApp() throws IOException {
hardwareStore = new HardwareStore();
}
/**
* Shows all items in the inventory.
*/
public void showAllItems() {
System.out.print(hardwareStore.getAllItemsFormatted());
}
/**
* This method will add items quantity with given number. If the item does
* not exist, it will call another method to add it.
*
*/
public void addItemQuantity() {
System.out.println("Please input the ID of item");
String idNumber = CONSOLE_INPUT.nextLine();
if (!idNumber.matches("[A-Za-z0-9]{5}")) {
System.out.println("Invalid ID Number: not proper format. "
+ "ID Number must be 5 alphanumeric characters.\n");
return;
}
int itemIndex = hardwareStore.findItem(idNumber);
if (itemIndex != -1) { // If item exists in the database
System.out.println("Item found in database. Please enter quantity to add.");
int quantity = CONSOLE_INPUT.nextInt();
if (quantity <= 0) {
System.out.println("Invalid quantity. "
+ "The addition amount must be larger than 0.\n");
return;
}
hardwareStore.addQuantity(itemIndex, quantity);
} else {
//If it reaches here, the item does not exist. We need to add new one.
System.out.println("Item with given number does not exist.\n");
// Enter name
System.out.println("\nPlease type the name of item.");
String name = CONSOLE_INPUT.nextLine();
// Entery category
String category = null;
System.out.println("\nPlease select the category of item.");
System.out.println("1: Door&Window\n2: Cabinet&Furniture\n3: Fasteners\n4: Structural\n5: Other");
int selection = CONSOLE_INPUT.nextInt();
switch (selection) {
case 1:
category = "Door&Window";
break;
case 2:
category = "Cabinet&Furniture";
break;
case 3:
category = "Fasteners";
break;
case 4:
category = "Structural";
break;
case 5:
category = "Other";
break;
default:
System.out.println("Invalid category number.");
return;
}
// Entery quantity
System.out.println("\nPlease type the quantity of the item.");
int quantity = CONSOLE_INPUT.nextInt();
if (quantity < 0) {
System.out.println("Invalid price. "
+ "The quantity cannot be smaller than 0.");
return;
}
// Enter price
System.out.println("\nPlease type the price of the item.");
float price = CONSOLE_INPUT.nextFloat();
if (price < 0) {
System.out.println("Invalid price. "
+ "The price cannot be smaller than 0.");
return;
}
hardwareStore.addNewItem(idNumber, name, category, quantity, price);
}
}
/**
* This method will remove the given quantity of an item with given number.
* If the item does not exist, it will show an appropriate message.
*/
public void removeItemQuantity() {
System.out.println("Please input the ID of item");
String idNumber = CONSOLE_INPUT.nextLine();
if (!idNumber.matches("[A-Za-z0-9]{5}")) {
System.out.println("Invalid ID Number: not proper format. "
+ "ID Number must be at least 5 alphanumeric characters.");
return;
}
int itemIndex = hardwareStore.findItem(idNumber);
int currentQuantity;
if (itemIndex == -1) {
System.out.println("Item does not exist.\n");
return;
} else {
currentQuantity = hardwareStore.getItem(itemIndex).getQuantity();
System.out.println("Current quantity: " + currentQuantity + "\n");
}
System.out.println("Please input the quantity to remove.");
int quantity = CONSOLE_INPUT.nextInt();
if (quantity > currentQuantity) {
System.out.println("Invalid quantity. "
+ "The removal amount must be smaller than current quantity.\n");
} else {
hardwareStore.removeQuantity(itemIndex, quantity);
}
}
/**
* This method can search item by a given name (part of name.
* Case-insensitive.) Will display all items with the given name.
*/
public void searchItemByName() {
System.out.println("Please input the name of item.\n");
String name = CONSOLE_INPUT.nextLine();
String output = hardwareStore.getMatchingItemsByName(name);
if (output == null) {
System.out.println("Item not found.");
} else {
System.out.println(output);
}
}
/**
* This method can search item below a certain quantity. Will display all
* items fits such condition.
*/
public void searchItemByQuantity() {
System.out.println("Please enter the quantity:\n");
int quantity = CONSOLE_INPUT.nextInt();
if (quantity < 0) {
System.out.println("Quantity should be at least 0.\n");
}
String output = hardwareStore.getMatchingItemsByQuantity(quantity);
if (output == null) {
System.out.println("No items found below given quantity.");
} else {
System.out.println(output);
}
}
public void saveDatabase() throws IOException {
hardwareStore.writeDatabase();
}
/**
* This method will begin the user interface console. Main uses a loop to
* continue executing commands until the user types '6'.
*
* #param args this program expects no command line arguments
* #throws Exception
*/
public static void main(String[] args) throws Exception {
MainApp app = new MainApp();
String welcomeMessage = "\nWelcome to the Hardware Store database. Choose one of the following functions:\n\n"
+ "\t1. Show all existing items in stock and their quantities.\n"
+ "\t2. Add a new quantity of a specific item to the stock.\n"
+ "\t3. Remove a certain quantity of a specific item type.\n"
+ "\t4. Search for an item (given its name or part of its name).\n"
+ "\t5. Show a list of all items below a certain quantity.\n"
+ "\t6. Exit program.\n";
System.out.println(welcomeMessage);
int selection = CONSOLE_INPUT.next().charAt(0);
CONSOLE_INPUT.nextLine();
while (selection != '6') {
switch (selection) {
case '1':
app.showAllItems();
break;
case '2':
app.addItemQuantity();
break;
case '3':
app.removeItemQuantity();
break;
case '4':
app.searchItemByName();
break;
case '5':
app.searchItemByQuantity();
break;
case 'h':
System.out.println(welcomeMessage);
break;
default:
System.out.println("That is not a recognized command. Please enter another command or 'h' to list the commands.");
break;
}
System.out.println("Please enter another command or 'h' to list the commands.\n");
selection = CONSOLE_INPUT.next().charAt(0);
CONSOLE_INPUT.nextLine();
}
CONSOLE_INPUT.close();
System.out.print("Saving database...");
app.saveDatabase();
System.out.println("Done!");
}
}
Here are my test classes in a test package
HardwareStoreTest.java
package test;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
import hardwarestore.*;
public class HardwareStoreTest {
public static HardwareStore hardwarestore = null;
#BeforeClass
public static void createEnvironment() throws IOException {
hardwarestore = new HardwareStore();
}
#AfterClass
public static void clearEnvironment() {
hardwarestore = null;
System.out.println("Environment cleared");
}
#Test
public static void testAddItem() {
hardwarestore.addNewItem("123543","sink","other",23,24.95f);
assertNotNull("Test Failed message", hardwarestore.getItem(0));
}
}
TestRunner.java
package test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(HardwareStoreTest.class);
if(result.getFailures().size()==0) {
System.out.println("All tests successfull!");
}else {
System.out.println("No. of failed test cases = "+ result.getFailures().size());
for(Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
}
}
Change your import at the top and the Test shouldn't be static.
import org.junit.Test
#Test
public void addNewItem(){
hardwarestore.addNewItem("123RT", "sink", "kitchen", 34, 4.51f);
assertNotNull("Test Failed Message", hardwarestore.getItem(0));
}

How to use methods from other classes

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.

Need help using arraylists in program?

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.

Dealing Cards Through a Single Array

I have to write a program to play a game of poker between two 'human' players. I have the main method (dealer) set up to ask for the first player's bet but I haven't been able to figure out how to call upon the Deck class to the deal method. I tried deck.deal(), etc. but nothing seems to go through. Ill post the classes that are involved below and I've taken note of where the code should call upon the deck in the Dealer class
public class Dealer
{
private Deck deck;
private Player[] players;
private String n;
Scanner scan = new Scanner(System.in);
public static final int NUMBER_OF_PLAYERS = 2;
/**
* Default constructor - creates and populates the Player array and the
* Deck object.
*/
public Dealer()
{
players = new Player[ NUMBER_OF_PLAYERS ]; //IMPORTANT players is the array
deck = new Deck();
// populate the array of players
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play()
{
System.out.println("Welcome to Poker!");
//Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players[0] = new Player(name);
players[0].getName(name);
//Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players[1] = new Player(name);
players[1].getName(name);
//First Player Goes
System.out.println(players[0].getName(n) + "'s Turn\n");
//Bet
System.out.println("Enter bet: ");
int bet = players[0].getBet(); //IMPORTANT players is the array and can call Player method as own
//Able to bet?
while(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 20;
if(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 1;
}
}
//Draw Cards/Deck
//*****NEED TO DEAL CARDS HERE*****
//*****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
//Compare
//Add to winner
//Add to loser
//Winner Goes ^^
} // method play
}
public class Deck
{
private int pointer = 0; // indicates the current position in the deck.
// This should begin with 0 (the first call)
// and increment every time a card is dealt.
private Card deck[] = new Card[CARDS_IN_DECK];
private Card tempDeck[] = new Card[CARDS_IN_DECK];
private Card Cards[] = new Card[5];
public static final int CARDS_IN_DECK = 52;
/**
* Instantiate an array of Cards and populate the array with 52 Card
* objects. The face values of the cards should be between 2 - 14.
* Values 2 - 10 represent the number cards. Values 11 - 14 represent
* Jack, Queen, King, and Ace, respectively. The suits should be as
* follows: 100 = Clubs, 200 = Diamonds, 300 = Hearts, and 400 = Spades.
* See the Card class for more information.
*
* You should both shuffle and cut the cards before this method
* concludes.
*/
public Deck()
{
int i = 0;
for(int a = 1; a <= 5; a++)
{
for(int b = 2; b <=14; b++)
{
deck[i] = new Card(a,b);
}
}
shuffle();
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random
* or fixed) and re-arrange the cards. For example, if you choose to
* cut at position 26, then the 27th - 52nd cards will be placed in the
* 1st - 26th positions. The 1st - 26th cards will be placed in the
* 27th - 52nd positions.
*/
public void cut()
{
int cut = 26;
int a = 0;
int b = 0;
for(int i = 0 ; i<cut; i++)
{
tempDeck[i] = new Card(a,b);
tempDeck[i] = deck[i+26];
tempDeck[i+26] = deck[i];
}
deck = tempDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return
* these in an array. You will need to maintain a pointer that lets
* you know where you are in the deck. You should make sure also
* to reshuffle and cut the deck and start over if there are not enough
* cards left to deal a hand.
*
* #return an array of 5 cards
*/
public Card[] deal(int[] args)
{
int i = 0;
int a = 0;
int b = 0;
Cards[i] = new Card(a,b);
for(i = 0; i < 1; i++)
{
Cards[pointer] = deck[pointer];
pointer++;
}
return Cards;
// this is a stub only - replace this!!!!
} // method deal
/**
* Get a card from the deck
*
* #param the position of the card you are retrieving
* #return the card object
*/
public Card getCard( int card )
{
Card oneCard = deck[pointer];
deck[pointer] = null;
pointer +=1;
return oneCard; // this is a stub only - replace this!!!
} // method getCard
/**
* Shuffle the deck. Randomly re-arrange the cards in the deck. There
* are plenty of algorithms for doing this - check out Google!!!
*/
public void shuffle()
{
int i, j, k;
int n = 15;
for ( k = 0; k < n; k++ )
{
i = (int) ( CARDS_IN_DECK * Math.random() ); // Pick 2 random cards
j = (int) ( CARDS_IN_DECK * Math.random() ); // in the deck
tempDeck[j] = deck[i];
tempDeck[i] = deck[j];
deck = tempDeck;
}
pointer = 0; // Reset current card to deal
} // end shuffle
} // class Deck
public class Player
{
private int bet;
private int chips;
private int totalChips = 0;
private Hand hand;
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the player's name
*/
public Player( String n )
{
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that
* the player has by the number of chips bet. Do not allow bets if
* there are not enough chips left.
*
* #param the number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet( int bet )
{
int chipsAB;
boolean canBet;
//Get Bet
getBet();
//See if player has enough chips for bet
if(totalChips >= bet)
{
canBet = true;
}
else
{
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/ //DONE
public int getBet()
{
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips())
{
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips()
{
for(int i = 0; i<1; )
{
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips()
{
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public Hand getHand()
{
return new Hand(); // this is a stub only - replace this!!!!
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName(String name)
{
String n = name;
return n; // this is a stub only - replace this!!!!
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon()
{
boolean won = false;
if(chips == 0)
{
won = true;
}
return won; // this is a stub - replace this!!!
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the
* Dealer)
*
* #param the hand dealt by the dealer
*/
public void setHand( Hand h )
{
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString()
{
String nameChips;
nameChips = (name + totalChips);
return nameChips; // this is a stub only - replace this!!!
} // method toString
/**
* We won the hand, so increase chips
*
* #param the number of chips won
*/
public int winHand()
{
int chipsAB = 0;
//if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
//else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
The code compiles for me, but I had to
create a class called Card with a constructor Card(int a, int b)
create a class called Hand
ignore the Javadoc errors.
After #param you should have the name of the parameter not the ...
The main method wasn't included, but other than that it compiles with a few changes.
I think I can get you going in the right direction but I don't have time to do all the work. I went a bit further and used Java collections to clarify / ease some of the use. A bunch of code updates here. Key points are Suit enum, Collections.shuffle, use of ArrayLists for the deck and hands, and the changes in the cut function. There is also a lot of opportunity for more error and bounds checking.
Stylistically, I'd suggest thinking about your object layout. Dealer is a specialization of Player, shuffle and cut might better be methods on Dealer (a Deck doesn't do those things to itself). Anyhow, for this update I didn't touch those things, just something to be aware of.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Dealer {
public static final int NUMBER_OF_PLAYERS = 2;
private Deck deck;
private List<Player> players = new ArrayList<Player>(NUMBER_OF_PLAYERS);
Scanner scan = new Scanner(System.in);
/**
* Default constructor - creates and populates the Player array and the Deck object.
*/
public Dealer() {
deck = new Deck();
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play() {
System.out.println("Welcome to Poker!");
// Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players.add(new Player(name));
// Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players.add(new Player(name));
// First Player Goes
System.out.println(players.get(0).getName() + "'s Turn\n");
// Bet
System.out.println("Enter bet: ");
int bet = players.get(0).getBet();
// Able to bet?
while (!players.get(0).bet(bet) || !players.get(1).bet(bet)) {
bet = 20;
if (!players.get(0).bet(bet) || !players.get(0).bet(bet)) {
bet = 1;
}
}
// Draw Cards/Deck
// *****NEED TO DEAL CARDS HERE*****
// *****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
for (Player player : players) {
player.setHand(deck.deal(5));
}
// Compare
// Add to winner
// Add to loser
// Winner Goes ^^
} // method play
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Player {
private int chips;
private int totalChips = 0;
private List<Card> hand = new ArrayList<Card>();
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the
* player's name
*/
public Player(String n) {
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that the player has by the number of chips bet. Do not allow
* bets if there are not enough chips left.
*
* #param the
* number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet(int bet) {
boolean canBet;
// Get Bet
getBet();
// See if player has enough chips for bet
if (totalChips >= bet) {
canBet = true;
} else {
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/
// DONE
public int getBet() {
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips()) {
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips() {
for (int i = 0; i < 1;) {
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips() {
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public List<Card> getHand() {
return hand;
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName() {
return name;
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon() {
return (chips > WINNING_CHIPS);
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the Dealer)
*
* #param the
* hand dealt by the dealer
*/
public void setHand(List<Card> dealtHand) {
hand = dealtHand;
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString() {
return "Name: " + name + ", Chips: " + chips;
} // method toString
/**
* We won the hand, so increase chips
*
* #param the
* number of chips won
*/
public int winHand() {
int chipsAB = 0;
// if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
// else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Deck {
public static final int CARDS_IN_DECK = 52;
private List<Card> deck = new ArrayList<Card>(CARDS_IN_DECK);
/**
* Constructor
*
* Instantiate an array of Cards and populate the array with 52 Card objects. The face values of the cards should be between 2 -
* 14. Values 2 - 10 represent the number cards. Values 11 - 14 represent Jack, Queen, King, and Ace, respectively.
*
* You should both shuffle and cut the cards before this method concludes.
*/
public Deck() {
for (Suit suit : Suit.values()) {
// I made the Ace equal to 1, but it's just preference
for (int value = 2; value <= 14; value++) {
deck.add(new Card(suit, value));
}
}
Collections.shuffle(deck);
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random or fixed) and re-arrange the cards. For example, if you
* choose to cut at position 26, then the 27th - 52nd cards will be placed in the 1st - 26th positions. The 1st - 26th cards
* will be placed in the 27th - 52nd positions.
*/
public void cut() {
Random rand = new Random();
int cutPoint = rand.nextInt(deck.size()) + 1;
List<Card> newDeck = new ArrayList<Card>(deck.size());
newDeck.addAll(deck.subList(cutPoint, deck.size()));
newDeck.addAll(deck.subList(0, cutPoint));
deck = newDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return these in an array. You will need to maintain a pointer that
* lets you know where you are in the deck. You should make sure also to reshuffle and cut the deck and start over if there are
* not enough cards left to deal a hand.
*
* #return an array of 5 cards
*/
public List<Card> deal(int size) {
List<Card> hand = new ArrayList<Card>(size);
hand.add(deck.remove(0));
return hand;
} // method deal
/**
* Get a card from the deck
*
* #param the
* position of the card you are retrieving
* #return the card object
*/
public Card getCard(int position) {
if (position >= 0 && position < deck.size()) {
return deck.remove(position);
}
else {
return null; // or throw an exception, or print an error or whatever
}
} // method getCard
} // class Deck
public class Card {
private Suit suit;
private int value;
public Card(Suit suit, int value) {
this.suit = suit;
this.value = value;
}
public Suit getSuit() {
return suit;
}
public int getValue() {
return value;
}
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}

Having problems doing Cartesian product

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.

Categories

Resources