Objects are being overwritten when adding a new Object to an array - java

I am working on an assignment for school and cannot figure why my items are being overwritten in my shopping cart class. If it were up to me id be using an arraylist but the assignment calls for an array of Items.
package jjobrien_assignement_4;
import java.util.Arrays;
import java.util.Scanner;
public class ShoppingCart extends Shopper{
private static final int DEFAULT_SIZE = 10;
String userName;
Item[] cart;
int itemCount = 0;
/**
* ShoppingCart default constructor
*/
public ShoppingCart(){
userName = "";
cart = new Item[DEFAULT_SIZE];
}
/**
* Shopping cart overloaded constructor
* #param aUserName
*/
public ShoppingCart(String aUserName){
userName = aUserName;
cart = new Item[DEFAULT_SIZE];
}
/**
* Adds a single item to the array cart[]
* #param cart
* #return
*/
public void addItem(Item theItem){
for(int i = 0; i < DEFAULT_SIZE; i++){
if(cart[i] == null){
System.out.print(i);
cart[i]= theItem;
itemCount += 1;
System.out.print(cart[i]);
break;
} //System.out.print(cart[i]);
}
}
public String removeItem(){
return "";
}
/**
*
* #param cleared
* #return cleared
* Will clear every object inside of the array cart[]
* by setting all valuse in the cart[] to null.
*/
public boolean clear(boolean cleared){
for(int i = 0; i < cart.length; i++){
cart[i] = null;
}
cleared = true;
itemCount = 0;
return cleared;
}
public String indexOf(){
return "";
}
/**
* Grabs single item from array to return to shopper
* #return
*/
public String getItem(){
String theItem = "";
for(int i = 0; i < itemCount; i++){
theItem = cart[i].getProductName();
}
return theItem;
}
public String showAll(String all){
for(int i = 0; i < itemCount; i++){
all += cart[i].getProductName() + " $"
+ cart[i].getPrice() + "\n";
}
return all;
}
/**
*
* #return
* Adds total cost and divides by item count to get avgCost
*/
public double showAverageCost(){
double avgCost = 0;
double totalCartCost = 0;
double singleItemCost = 0;
for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}
avgCost = totalCartCost/itemCount;
return avgCost;
}
/**
*
* #param totalCartCost
* #return
* Calculates total cost by getting each price
* of all existing items in the array cart[].
*/
public double totalCost(double totalCartCost){
double singleItemCost = 0;
for(int i = 0; i < itemCount; i++){
singleItemCost = cart[i].getPrice();
totalCartCost = totalCartCost + singleItemCost;
}
return totalCartCost;
}
/**
* #return itemCount
* Counts how many items are in the shoppers cart
*/
public int countItems(){
int numOfItems = 0;
for(int i = 0; i < itemCount; i++){
numOfItems = numOfItems + 1;
}
return numOfItems;
}
}
}
{package jjobrien_assignement_4;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Shopper {
public final static String MENU = "\nSelect an option: \nType \"add\" to add an Item to the cart\n" +
"Type \"count\" to determine the total number of Items in the" +
"cart\n" +
"Type \"total cost\" to determine the total cost of Items in" +
"the cart\n" +
"Type \"show all\" to display the contents of the cart\n" +
"Type \"show average cost\" to display the average price of" +
"the contents of the cart\n" +
"Type \"cheapest\" to display the Item with the lowest price" +
"in the cart\n" +
"Type \"highest\" to display the Item with the highest price" +
"in the cart\n" +
"Type \"remove\" to remove a specific Item from the cart\n" +
"Type \"clear\" to remove all Items from the cart\n" +
"Type \"quit\" to exit the program: ";
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
/*
cart[0] = new Item("Milk", 3.00);
cart[1] = new Item("Eggs", 4.25);
cart[2] = new Item("Bread", 2.50);
*/
boolean cleared = false;
boolean done = false;
double totalCartCost = 0.0;
String userName = "";
String userOption = "No option yet";
JOptionPane.showMessageDialog(null, "Welcome to the shopping cart!");
userName = JOptionPane.showInputDialog(null, "Please enter your name: ");
ShoppingCart newCart = new ShoppingCart(userName);
//While to display menu to customer and call methods based on user input
while(!done){
userOption = JOptionPane.showInputDialog(null, MENU);
if(userOption.equals("quit")){
if(quit(done) == true){
JOptionPane.showMessageDialog(null, "Thank you for using the Shopping Cart program!\n");
done = true;
}else if(quit(done) == false){
done = false;
}
}else if(userOption.equals("add")){
addItem(keyboard, newCart);
}else if(userOption.equals("count")){
}else if(userOption.equals("total cost")){
findTotalCost(newCart);
}else if(userOption.equals("show all")){
showAllItems(newCart);
}else if(userOption.equals("show average cost")){
showAverage(newCart);
}else if(userOption.equals("cheapest")){
//getCheapest();
}else if(userOption.equals("highest")){
//getHighest();
}else if(userOption.equals("remove")){
//remove();
}else if(userOption.equals("clear")){
clear(cleared, newCart);
}
}
}
/**
* Exits the program
*/
public static boolean quit(boolean isDone){
isDone = true;
return isDone;
}
/**
* Calls shopping cart class to add a single item to the array
* #param keyboard
* #param theCart
*/
public static void addItem(Scanner keyboard, ShoppingCart theCart){
String theItem = "";
String tempPrice = "";
Double thePrice = 0.0;
Item temp = null;
theItem = JOptionPane.showInputDialog(null, "Enter product name: ");
tempPrice = JOptionPane.showInputDialog(null, "Enter the price of " + theItem + ": ");
thePrice = Double.parseDouble(tempPrice);
temp = new Item(theItem, thePrice);
if(temp != null){
theCart.addItem(temp);
}
}
/**
* Will call ShoppingCart Clear Method
* #param cleared
* #param theCart
* #return
*/
public static boolean clear(boolean cleared, ShoppingCart theCart){
theCart.clear(cleared);
JOptionPane.showMessageDialog(null, "Your cart was cleared");
return cleared;
}
/**
* will call totalCost method from shopping cart class
* to add the total cost of all items stored in cart[]
* #param theCart
*/
public static void findTotalCost( ShoppingCart theCart){
double totalCost = 0;
JOptionPane.showMessageDialog(null, "Total cost: "
+ theCart.totalCost(totalCost));
}
/**
* Will print every item with their corresponding price
* in the cart[] array
*/
public static void showAllItems(ShoppingCart theCart){
String all = "";
JOptionPane.showMessageDialog(null, theCart.showAll(all));
}
/**
* calls shopping cart class to get average cost or all items
* in the current cart
*/
public static void showAverage(ShoppingCart theCart){
JOptionPane.showMessageDialog(null, theCart.showAverageCost());
}
}
}
{package jjobrien_assignement_4;
public class Item {
private static String productName;
private static double price;
public Item(){
productName = "No Name yet";
price = 0;
}
public Item(String aProductName, double aPrice){
setProductName(aProductName);
setPrice(aPrice);
}
public double getPrice(){
return price;
}
public String getProductName(){
return productName;
}
public double setPrice(double aPrice){
price = aPrice;
return aPrice;
}
public String setProductName(String aProductName){
productName = aProductName;
return aProductName;
}
public java.lang.String toString(){
String text = "";
text += productName.toString();
return text;
}
}
}

Your Item class uses static variables to store its values.
A static variable is class-level - there is only one instance of that variable which is shared by every instance of your class.
When you change the values of your Item (such as when creating a new Item), you are in fact changing the static variables - effectively setting your new values for all Item objects.
Replacing your static variables with standard member variables should resolve your issues:
private String productName;
private double price;
Note that Eclipse will automatically generate constructors and setters using the syntax:
public void setSomething(String something) {
this.something = something;
}
and Eclipse should also give you a warning if you attempt to assign to a static variable in this way (because you are using a static variable in a non-static context.)
I'm not sure about other IDEs - but they should do something similar.

Related

Not sure why i'm getting an java.util.NoSuchElementException error

I am currently working on a program where I take information from a text document, then I print it out into another file and from java but halfway through, i'm getting an no such exception error and i'm not sure why.
Tester code:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class HurricaneSelectorTester
{
public static void main (String [ ] args) throws IOException
{
//File scanner
File fileName = new File("HurricaneData.txt");
Scanner inFile = new Scanner(fileName);
PrintWriter outputFile = new PrintWriter(new File("OutputData.txt"));
Scanner in;
in = new Scanner(System.in);
//construct a Scanner object with one line
//Declare variables
int arrayLength = 156;
int [] years = new int[156];
int index = 0;
int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int cat5 = 0;
double windAvg = 0;
double windTotal = 0;
double windMax = Integer.MIN_VALUE;
double windMin = Integer.MAX_VALUE;
double pressureAvg = 0;
double pressureTotal = 0;
int pressureMax = Integer.MIN_VALUE;
int pressureMin = Integer.MAX_VALUE;
double catAvg = 0;
double catTotal = 0;
int catMax = Integer.MIN_VALUE;
int catMin = Integer.MAX_VALUE;
int rangeMax = 0;
int rangeMin = 0;
//Ask for range
System.out.println("Please enter minimum year (1995-2015)");
rangeMin = in.nextInt();
System.out.println("Please enter maximum year (1995-2015)");
rangeMax = in.nextInt();
//Print title info
System.out.println("Hurricanes "+ ""+ rangeMin + "-" + "" + rangeMax);
System.out.println();
System.out.println("Year Hurricane Category Pressure (mb) Wind Speed (mph)");
System.out.println("****************************************************************");
ArrayList<HurricaneSelector> hurricanes = new ArrayList<HurricaneSelector>();
//Load all the info into the arrays
while (inFile.hasNext())
{
hurricanes.add(new HurricaneSelector(inFile.nextInt(),inFile.next(),inFile.nextInt(),inFile.nextInt(),inFile.next()));
}
for(index = 0; index < 156; index++){
years[index] = inFile.nextInt();
}
inFile.close();
HurricaneSelector dataRecord; //Data record for HurricaneSelector
for(index = 0; index < 156; index++)
{if(years[index]>= rangeMin && years[index]<= rangeMax){
dataRecord = hurricanes.get(index);
dataRecord.calcCategoriesAndTotals();
dataRecord.calcNewWind();
dataRecord.calcWindMax();
dataRecord.calcWindMin();
dataRecord.calcPressureMax();
dataRecord.calcPressureMin();
dataRecord.calcCategoryMax();
dataRecord.calcCategoryMin();
}
}
dataRecord = hurricanes.get(index);
dataRecord.calcWindAverage();
dataRecord.calcCategoryAverage();
dataRecord.calcPressureAverage();
//Print out data
outputFile.println("Year Name Category Pressure Wind Speed");
for (index = 0; index < 156; index++){
if(years[index]>= rangeMin && years[index]<= rangeMax){
System.out.println(" "+hurricanes.get(index));
System.out.println();
outputFile.println(" "+hurricanes.get(index));
}
}
outputFile.close();
System.out.println("****************************************************************");
System.out.print(" Average:");
System.out.printf("%15.1f%13.1f%20.2f",catAvg,pressureAvg,windAvg);
System.out.println();
System.out.print(" Maximum:");
System.out.printf("%15d%13d%20.2f",catMax , pressureMax , windMax);
System.out.println();
System.out.print(" Minimum:");
System.out.printf("%15d%13d%20.2f",catMin , pressureMin , windMin);
System.out.println();
System.out.println();
System.out.println("Summary of categories");
System.out.println(" Category 1: " + cat1);
System.out.println(" Category 2: " + cat2);
System.out.println(" Category 3: " + cat3);
System.out.println(" Category 4: " + cat4);
System.out.println(" Category 5: " + cat5);
}
Methods:
public class HurricaneSelector
{
private int myYear, myPressure, myWind, myRangeMin, myRangeMax, myCategory, category1, category2,category3, category4, category5;
private String myMonth, myName;
private double myNewWind;
public double myWindAverage, myPressureAverage, myCategoryAverage, myWindMax = Integer.MIN_VALUE,
myWindMin = Integer.MAX_VALUE, myPressureMax = Integer.MIN_VALUE, myPressureMin = Integer.MAX_VALUE,
myCatMax = Integer.MIN_VALUE,myCatMin = Integer.MAX_VALUE;
public int total;
/**
* Constructor for objects of type HurricaneSelector
* #param year is the year of the hurricane
* #param month is the month of the hurricane
* #param pressure is the pressure of the hurricane
* #param wind is the wind speed of the hurricane
* #param name is the name of the hurricane
*/
HurricaneSelector(int year, String month, int pressure, int wind, String name)
{
myYear = year;
myMonth = month;
myPressure = pressure;
myWind = wind;
myName = name;
}
/**
* Mutator method to calculate the wind speed in mph (no parameters)
*/
public void calcNewWind()
{
myNewWind = (myWind* 1.15);
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcWindMax()
{
if (myNewWind > myWindMax){
myWindMax = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcWindMin()
{
if (myNewWind > myWindMin){
myWindMin = myNewWind;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcPressureMax()
{
if (myPressure > myPressureMax){
myPressureMax = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcPressureMin()
{
if (myPressure > myPressureMin){
myPressureMin = myPressure;
}
}
/**
* Mutator method to calculate if the value is the new Maximum (no parameters)
*/
public void calcCategoryMax()
{
if (myCategory > myCatMax){
myCatMax = myCategory;
}
}
/**
* Mutator method to calculate if the value is the new Minimum (no parameters)
*/
public void calcCategoryMin()
{
if (myCategory > myCatMin){
myCatMin = myCategory;
}
}
/**
* Mutator method to calculate which category the Hurricane fits into and get the totals(no parameters)
*/
public void calcCategoriesAndTotals()
{
myWindAverage += myNewWind;
myPressureAverage += myPressure;
if (myNewWind > 74 && myNewWind < 95)
{
myCategory = 1;
myCategoryAverage += myCategory;
category1++;
}
else if(myNewWind > 96 && myNewWind < 110)
{
myCategory = 2;
myCategoryAverage += myCategory;
category2++;
}
else if(myNewWind > 111 && myNewWind < 129)
{
myCategory = 3;
myCategoryAverage += myCategory;
category3++;
}
else if(myNewWind > 130 && myNewWind < 156)
{
myCategory = 4;
myCategoryAverage += myCategory;
category4++;
}
else if(myNewWind > 157)
{
myCategory = 5;
myCategoryAverage += myCategory;
category5++;
}
total++;
}
/**
* Mutator method to calculate the wind speed average (no parameters)
*/
public void calcWindAverage()
{
myWindAverage = myWindAverage/total;
}
/**
* Mutator method to calculate the category average (no parameters)
*/
public void calcCategoryAverage()
{
myCategoryAverage = myCategoryAverage/total;
}
/**
* Mutator method to calculate the pressure average (no parameters)
*/
public void calcPressureAverage()
{
myPressureAverage = myPressureAverage/total;
}
/**
* Getter method to return the year of the hurricane (no parameters)
*/
public int getYear()
{
return myYear;
}
/**
* Getter method to return the month of the hurricane (no parameters)
*/
public String getMonth()
{
return myMonth;
}
/**
* Getter method to return the pressure of the hurricane (no parameters)
*/
public int getPressure()
{
return myPressure;
}
/**
* Getter method to return the wind speed of the hurricane (no parameters)
*/
public double getNewWind()
{
return myNewWind;
}
/**
* Getter method to return the name of the hurricane (no parameters)
*/
public String getName()
{
return myName;
}
/**
* Getter method to return the wind average (no parameters)
*/
public Double getWindAverage()
{
return myWindAverage;
}
/**
* Getter method to return the pressure average (no parameters)
*/
public Double getPressureAverage()
{
return myPressureAverage;
}
/**
* Getter method to return the category average (no parameters)
*/
public Double getCategoryAverage()
{
return myCategoryAverage;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getWindMax()
{
return myWindMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getWindMin()
{
return myWindMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getPressureMax()
{
return myPressureMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getPressureMin()
{
return myPressureMin;
}
/**
* Getter method to return the category maximum (no parameters)
*/
public Double getCategoryMax()
{
return myCatMax;
}
/**
* Getter method to return the category minimum (no parameters)
*/
public Double getCategoryMin()
{
return myCatMax;
}
public String toString(){
return String.format("%10d%10s%10d%10d%10.2f",myYear,myName, myCategory, myPressure, myNewWind);
}
The links to the text files: https://drive.google.com/file/d/1eazHCEwT0Se6hfx2SDilqCqY8ZMi4E9k/view?usp=sharing
https://drive.google.com/file/d/1CN0JnlbMWNEB7B4nomgJ_-6mkwR1wgYc/view?usp=sharing
I know there are other problems with the code such as useless variables, formatting, etc. but right now I need to fix the program so that it can actually run and print out most of the data right now.
You need to reset() the Scanner because you've reached the end in your loop, and you want to start from the beginning for the next set of operations.
From JavaSE docs:
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

Java Homework Assignment Linked List

Thank you for everyone who got me on my feet. However, My cutSplice method is inefficient. I need to be able to modify it easy so that i can do the reverse method.
developing a single Java class (LinkedDnaStrand) that uses a linked list of nodes to represent a strand of DNA that supports splicing. Each node in the list will contain a string of one or more nucleotides (A, C, G, or T). The class will be responsible for operations such as append() and cutSplice(), which model real-world restriction enzyme processing.
EX. tt will be replaced with cat. (Better LinkedDnaStrandTester)
package dnasplicing;
public class DnaSequenceNode {
public String dnaSequence;
public DnaSequenceNode previous;
public DnaSequenceNode next;
public DnaSequenceNode(String initialDnaSequence) {
dnaSequence = initialDnaSequence;
}
}
package dnasplicing;
public class LinkedDnaStrand implements DnaStrand {
int nodeCount = 0;
int appendCount = 0;
long nucleotideCount = 0;
String sequenceString;
DnaSequenceNode cursor, head, tail;
public LinkedDnaStrand(String dnaSequence) {
DnaSequenceNode newNode = new DnaSequenceNode(dnaSequence);
head = newNode;
cursor = head;
tail = head;
head.previous = null;
tail.previous = null;
sequenceString = dnaSequence;
nodeCount++;
}
public String toString() {
String result = "";
DnaSequenceNode n = head;
while (n != null) {
result += n.dnaSequence;
n = n.next;
}
return result;
}
#Override
public long getNucleotideCount() {
nucleotideCount = sequenceString.length();
return nucleotideCount;
}
#Override
public void append(String dnaSequence) {
if (dnaSequence != null && dnaSequence.length() > 0) {
tail.next = new DnaSequenceNode(dnaSequence);
tail.next.previous = tail;
tail = tail.next;
sequenceString += dnaSequence;
appendCount++;
nodeCount++;
}
}
#Override
public DnaStrand cutSplice(String enzyme, String splicee) {
boolean frontSplice = false;
boolean backSplice = false;
if (sequenceString.startsWith(enzyme)) {
frontSplice = true;
}
if (sequenceString.endsWith(enzyme)) {
backSplice = true;
}
String[] dnaParts = sequenceString.split(enzyme);
LinkedDnaStrand newLinkedStrand = null;
if (frontSplice == true) {
newLinkedStrand = new LinkedDnaStrand(splicee);
// newLinkedStrand.append(dnaParts[0]);
for (int i = 1; i < dnaParts.length; i++) {
newLinkedStrand.append(dnaParts[i]);
if (i < dnaParts.length - 1) {
newLinkedStrand.append(splicee);
}
}
} else {
newLinkedStrand = new LinkedDnaStrand(dnaParts[0]);
for (int index = 1; index < dnaParts.length; index++) {
newLinkedStrand.append(splicee);
newLinkedStrand.append(dnaParts[index]);
}
}
if (backSplice == true) {
newLinkedStrand.append(splicee);
}
// sequenceString = newLinkedStrand.toString();
return newLinkedStrand;
}
#Override
public DnaStrand createReversedDnaStrand() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getAppendCount() {
// TODO Auto-generated method stub
return appendCount;
}
#Override
public DnaSequenceNode getFirstNode() {
return head;
}
#Override
public int getNodeCount() {
return nodeCount;
}
}
package dnasplicing;
public interface DnaStrand {
/**
* NOTE: Your LinkedDnaStrand class must have a constructor that takes one parameter: String dnaSequence. When the
* constructor completes, your linked list should have just one node, and it should contain the passed-in
* dnaSequence. For example, if the following line of code was executed:
*
* LinkedDnaStrand strand = new LinkedDnaStrand("GATTACA");
*
* Then strand's linked list should look something like (previous pointers not shown):
*
* first -> "GATTACA" -> null
*
* The first line of this constructor should look like:
*
* public LinkedDnaStrand(String dnaSequence) {
*/
/**
* #return The entire DNA sequence represented by this DnaStrand.
*/
public String toString();
/**
* Returns the number of nucleotides in this strand.
*
* #return the number of base-pairs in this strand
*/
public long getNucleotideCount();
/**
* Appends the given dnaSequence on to the end of this DnaStrand. appendCount is incremented. Note: If this
* DnaStrand is empty, append() should just do the same thing as the constructor. In this special case, appendCount
* is not incremented.
*
* #param dnaSequence
* is the DNA string to append
*/
public void append(String dnaSequence);
/**
* This method creates a <bold>new</bold> DnaStrand that is a clone of the current DnaStrand, but with every
* instance of enzyme replaced by splicee. For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
* cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not
* shown):
*
* first -> "TT" -> "TTAAGG" -> "CC" -> null
*
* <b>NOTE</b>: This method will only be called when the linke list has just one node, and it will only be called
* once for a DnaStrand. This means that you do not need to worry about searching for enzyme matches across node
* boundaries.
*
* #param enzyme
* is the DNA sequence to search for in this DnaStrand.
*
* #param splicee
* is the DNA sequence to append in place of the enzyme in the returned DnaStrand
*
* #return A <bold>new</bold> strand leaving the original strand unchanged.
*/
public DnaStrand cutSplice(String enzyme, String splicee);
/**
* Returns a <bold>new</bold> DnaStrand that is the reverse of this strand, e.g., if this DnaStrand contains "CGAT",
* then the returned DnaStrand should contain "TAGC".
*
* #return A <bold>new</bold> strand containing a reversed DNA sequence.
*/
public DnaStrand createReversedDnaStrand();
/**
*
* #return The number of times that the DnaStrand has been appended via a call to append() or during the cutSplice()
* operation. Note that the very first time that a DnaStrand is given a DNA sequence is not to be counted as
* an append.
*/
public int getAppendCount();
/**
* This is a utility method that allows the outside world direct access to the nodes in the linked list.
*
* #return The first DnaSequenceNode in the linked list of nodes.
*/
public DnaSequenceNode getFirstNode();
/**
* This is a utility method that allows the outside world to determine the number of nodes in the linked list.
*
* #return
*/
public int getNodeCount();
}
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import java.io.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import dnasplicing.*;
// Updated 25-Feb-2016 at 6:10pm
public class LinkedDnaStrandTester {
static String ecoliSmall = "AGCTTTTCATTAGCCCGCAGGCAGCCCCACACCCGCCGCCTCCTGCACCGAGAGAGATGGAATAAAGCCCTTGAACCAGC";
static String ecor1 = "GAATTC"; // restriction enzyme
public static int totalScore = 0;
public static int extraCredit = 0;
public static InputStream defaultSystemIn;
public static PrintStream defaultSystemOut;
public static PrintStream defaultSystemErr;
public static String newLine = System.getProperty("line.separator");
public void testCutSplice() {
String enzyme = "GAT";
String splicee = "TTAAGG";
String[] strands = { "TTGATCC", "TCGATCTGATTTCCGATCC", "GATCTGATCTGAT" };
String[][] recombinants = { { "TT", "TTAAGG", "CC" },
{ "TC", "TTAAGG", "CT", "TTAAGG", "TTCC", "TTAAGG", "CC" },
{ "TTAAGG", "CT", "TTAAGG", "CT", "TTAAGG" } };
for (int ndx = 0; ndx < strands.length; ndx++) {
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(strands[ndx]);
DnaStrand newlinkedStrand = linkedStrand.cutSplice(enzyme, splicee);
assertEquals("cutSplice(" + enzyme + ", " + splicee + ") failed at ndx = " + ndx, join(recombinants[ndx]),
newlinkedStrand.toString());
assertEquals("Append counts didn't match for ndx = " + ndx, recombinants[ndx].length - 1,
newlinkedStrand.getAppendCount());
// Verify that each node contains the correct DNA sequence
DnaSequenceNode node = newlinkedStrand.getFirstNode();
for (int nodeNdx = 0; nodeNdx < recombinants.length; nodeNdx++) {
assertNotNull("For strand " + ndx + ", there is no node at position " + nodeNdx, node);
assertEquals("For strand " + ndx + ", the sequences don't match at position " + nodeNdx,
recombinants[ndx][nodeNdx], node.dnaSequence);
node = node.next;
}
}
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice of (part of) the E Coli sequence using the ECoR1
* restriction enzyme and insulin as a splicee.
*/
#Test
public void testSpliceInsulinIntoEcoli() {
for (int testNumber = 1; testNumber <= 5; testNumber++) {
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the
// first third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
DnaStrand newL = linkedStrand.cutSplice(ecor1, insulin);
DnaStrand newS = simpleStrand.cutSplice(ecor1, insulin);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
assertEquals(newS.getAppendCount(), newL.getNodeCount() - 1);
// Verify that the nodes exist
DnaSequenceNode node = newL.getFirstNode();
for (int ndx = 0; ndx < newL.getNodeCount(); ndx++) {
assertNotNull("There is no node at position " + ndx, node);
node = node.next;
}
}
totalScore += 10;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice efficiently.
*/
#Test
public void testSplicingTime() {
// First verify that the LinkedDnaStrand cutSplice works
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the first
// third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
String splicee = createRandomDnaSequence(1024 * 1024, 1024 * 1024);
DnaStrand newL = linkedStrand.cutSplice(ecor1, splicee);
DnaStrand newS = simpleStrand.cutSplice(ecor1, splicee);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
// Now verify that it can cut and splice N times in less than T seconds
int numSplicings = 200;
double maxTime = 2.0;
double start = nanoTime();
for (int i = 0; i < numSplicings; i++)
newL = linkedStrand.cutSplice(ecor1, splicee);
double end = nanoTime();
double time = ((end - start) / 1e9);
// out.println("Time = " + time);
assertTrue("Time limit of " + maxTime + " seconds exceeded. Time to splice " + numSplicings + " times was "
+ time + " seconds.", time <= maxTime);
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can create a new, reversed LinkedDnaStrand.
*/
#Test
public void testReverse() {
String dnaSequence = createRandomDnaSequence(50, 100);
String dnaToAppend = createRandomDnaSequence(5, 10);
int numTimesToAppend = (int) (random() * 10);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(dnaSequence);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(dnaSequence);
for (int ndx = 0; ndx < numTimesToAppend; ndx++) {
linkedStrand.append(dnaToAppend);
simpleStrand.append(dnaToAppend);
}
assertEquals(simpleStrand.toString(), linkedStrand.toString());
assertEquals(numTimesToAppend + 1, linkedStrand.getNodeCount());
LinkedDnaStrand rl = (LinkedDnaStrand) linkedStrand.createReversedDnaStrand();
// Verify that the original linked strand wasn't changed
DnaSequenceNode node = linkedStrand.getFirstNode();
int nodeNdx = 0;
while (node != null) {
assertEquals("Sequences don't match at node index " + nodeNdx, nodeNdx == 0 ? dnaSequence : dnaToAppend,
node.dnaSequence);
node = node.next;
nodeNdx++;
}
// Verify that the new strand string is reversed
assertEquals(simpleStrand.createReversedDnaStrand().toString(), rl.toString());
totalScore += 10;
// If the new strand has a reverse order of nodes and sequences within each node, give extra
// credit
int numNodes = linkedStrand.getNodeCount();
if (numNodes == rl.getNodeCount()) {
// Build array of reversed dna strings from original LinkedDnaStrand. Start at end of
// array and move toward
// start
node = linkedStrand.getFirstNode();
String[] reversedDnaSequences = new String[linkedStrand.getNodeCount()];
nodeNdx = numNodes - 1;
while (node != null) {
reversedDnaSequences[nodeNdx] = reverse(node.dnaSequence);
node = node.next;
nodeNdx--;
}
// Verify that the reversed list's nodes contain the same data as in the array
node = rl.getFirstNode();
nodeNdx = 0;
while (node != null) {
if (!node.dnaSequence.equals(reversedDnaSequences[nodeNdx]))
break;
node = node.next;
nodeNdx++;
}
if (nodeNdx == linkedStrand.getNodeCount())
extraCredit += 5;
}
}
private String[] createRandomDnaSequences(int numDnaSequences, int minLength, int maxLength) {
String[] dnaSequences = new String[numDnaSequences];
for (int ndx = 0; ndx < numDnaSequences; ndx++)
dnaSequences[ndx] = createRandomDnaSequence(minLength, maxLength);
return dnaSequences;
}
private String createRandomDnaSequence(int minLength, int maxLength) {
return RandomStringUtils.random((int) (random() * (maxLength - minLength) + minLength), "ACGT");
}
#BeforeClass
public static void beforeTesting() throws Exception {
totalScore = 0;
extraCredit = 0;
}
#AfterClass
public static void afterTesting() {
out.println("Estimated score (w/o late penalties, etc.) = " + totalScore);
out.println("Estimated extra credit (assuming on time submission) = " + extraCredit);
}
#Before
public void setUp() throws Exception {
defaultSystemIn = System.in;
defaultSystemOut = System.out;
defaultSystemErr = System.err;
}
#After
public void tearDown() throws Exception {
System.setIn(defaultSystemIn);
System.setOut(defaultSystemOut);
System.setErr(defaultSystemErr);
}
public void sendToStdinOfTestee(String message) {
System.setIn(new ByteArrayInputStream(message.getBytes()));
}
}
So I don't have some of the classes like the node class you are using so I cannot write the actual code but i will give you some pseudo code.
public String toString(){
String result = "";
Node n = start;
while(n != null){
string += n.data;
}
return result;
}
public long getNucleotideCount() {
long result = 0;
Node n = start;
while(n != null){
result += n.data.length();
}
return result;
}
public void append(String dnaSequence) {
end.next = new Node(dnaSequence);
end = end.next;
appendCount++;
}
public DnaStrand cutSplice(String enzyme, String splice) {
// For this I think it would be best to assemble into string then use replace
Node n = start;
String result = "";
while(n != null){
result += n.data;
}
result = result.replace(enzyme, splice)
return new DnaStrand(result);
}
The reverse method would be similar to cutSplice. Assemble to string, manipulate, then return new strand. If you need more help LMK.

Way to reset card game?

I'm making a game similar to solitaire, and when the user recognizes they have lost I have a button to reset the game. Currently I'm unsure how I can reset the game. I know ill have to make a new deck and clear my array to recreate everything as if the game was starting for the first time, but I don't know how to do this. How can I reset my game when a user presses reset?
/**
* This is a class that tests the Deck class.
*/
public class DeckTester {
/**
* The main method in this class checks the Deck operations for consistency.
* #param args is not used.
*/
public static void main(String[] args) {
Board board = new Board();
board.startGame();
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* The Deck class represents a shuffled deck of cards.
* It provides several operations including
* initialize, shuffle, deal, and check if empty.
*/
public class Deck {
/**
* cards contains all the cards in the deck.
*/
private List<Card> cards;
/**
* size is the number of not-yet-dealt cards.
* Cards are dealt from the top (highest index) down.
* The next card to be dealt is at size - 1.
*/
private int size;
/**
* Creates a new <code>Deck</code> instance.<BR>
* It pairs each element of ranks with each element of suits,
* and produces one of the corresponding card.
* #param ranks is an array containing all of the card ranks.
* #param suits is an array containing all of the card suits.
* #param values is an array containing all of the card point values.
*/
ArrayList<Card> cardList = new ArrayList<>();
String[] ranks = {"Ace","Two","Three","Four","Five","Six" , "Seven" , "Eight","Nine","Ten", "Jack", "Queen","King"};
String[] suits = {"spades" , "diamonds" , "clubs" , "hearts"};
int[] values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
boolean selected = false;
public Deck() {
cards = new ArrayList<Card>();
for (int j = 0; j < ranks.length; j++) {
for (String suitString : suits) {
cards.add(new Card(ranks[j], suitString, values[j], selected));
}
}
size = cards.size();
}
public Card nextCard() {
if(cards.size() > 0) {
System.out.println(cards.get(0).toString());
return cards.remove(0);
}else{
return null;
}
}
/**
* Determines if this deck is empty (no undealt cards).
* #return true if this deck is empty, false otherwise.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Accesses the number of undealt cards in this deck.
* #return the number of undealt cards in this deck.
*/
public int size() {
return cards.size();
}
/**
* Randomly permute the given collection of cards
* and reset the size to represent the entire deck.
*/
List<Card> shuffledDeck;
ArrayList<Integer> usedNumbers = new ArrayList<Integer>();
public void shuffle() {
shuffledDeck = new ArrayList<>();
Random random = new Random();
for(usedNumbers.size(); usedNumbers.size() < 52;) {
int randomNum = random.nextInt(52);
if(!usedNumbers.contains(randomNum)) {
shuffledDeck.add(usedNumbers.size(), cards.get(randomNum));
usedNumbers.add(randomNum);
}
}
size = shuffledDeck.size();
cards = shuffledDeck;
}
/**
* Generates and returns a string representation of this deck.
* #return a string representation of this deck.
*/
#Override
public String toString() {
String rtn = "size = " + size + "\nUndealt cards: \n";
for (int k = cards.size() - 1; k >= 0; k--) {
rtn = rtn + cards.get(k);
if (k != 0) {
rtn = rtn + ", ";
}
if ((size - k) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\nDealt cards: \n";
for (int k = cards.size() - 1; k >= size; k--) {
rtn = rtn + cards.get(k);
if (k != size) {
rtn = rtn + ", ";
}
if ((k - cards.size()) % 2 == 0) {
// Insert carriage returns so entire deck is visible on console.
rtn = rtn + "\n";
}
}
rtn = rtn + "\n";
return rtn;
}
}
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Board extends JFrame implements ActionListener {
Deck deck = new Deck();
Card card;
JPanel buttonPanel = new JPanel();
JPanel menuPanel = new JPanel();
JButton cardOne = new JButton();
JButton cardTwo = new JButton();
JButton cardThree = new JButton();
JButton cardFour = new JButton();
JButton cardFive = new JButton();
JButton cardSix = new JButton();
JButton cardSeven = new JButton();
JButton[] buttons = {cardOne, cardTwo, cardThree, cardFour, cardFive, cardSix, cardSeven};
int winCount = 0;
int lossCount = 0;
int deckCount = 52;
JButton replace = new JButton("Replace");
JButton reset = new JButton("Reset");
JLabel cardsLeft = new JLabel("Cards left:" + deckCount);
JLabel winLossLabel = new JLabel("Win: " + winCount + "\tLoss: " + lossCount);
public Board() {
initGUI();
}
ArrayList<Card> boardArray = new ArrayList<>();
public void startGame() {
deck.shuffle();
Card card;
for(int i = 0 ; i <=6 ; i++) {
boardArray.add(card = deck.nextCard());
buttons[i].setIcon(card.cardImage);
}
}
public void initGUI() {
setTitle("Elevens");
setLayout(new GridLayout(1,2));
buttonPanel.setLayout(new GridLayout(2,4));
menuPanel.setLayout(new GridLayout(4,1));
setResizable(false);
buttonPanel.add(cardOne);
buttonPanel.add(cardTwo);
buttonPanel.add(cardThree);
buttonPanel.add(cardFour);
buttonPanel.add(cardFive);
buttonPanel.add(cardSix);
buttonPanel.add(cardSeven);
menuPanel.add(replace);
menuPanel.add(reset);
menuPanel.add(cardsLeft);
menuPanel.add(winLossLabel);
add(buttonPanel);
add(menuPanel);
for(int i = 0; i < buttons.length; i++){
buttons[i].addActionListener(this);
}
replace.addActionListener(this);
reset.addActionListener(this);
replace.setSize(new Dimension (100,10));
pack();
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(600,300);
}
ImageIcon selectedIcon;
Boolean selected = false;
String newPathString;
int buttonNumber;
public void getPath(int buttonNumber) {
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if(boardArray.get(buttonNumber).rank() == "Ace" || boardArray.get(buttonNumber).rank() == "Jack" || boardArray.get(buttonNumber).rank() == "Queen" || boardArray.get(buttonNumber).rank() == "King") {
newPathString = path + boardArray.get(buttonNumber).rank() + boardArray.get(buttonNumber).suit() + "S.GIF";
}else{
newPathString = path + Integer.toString(boardArray.get(buttonNumber).pointValue()) + boardArray.get(buttonNumber).suit() + "S.GIF";
}
selectedIcon = new ImageIcon(newPathString);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == cardOne) {
if(boardArray.get(0).selected == false) {
getPath(0);
buttons[0].setIcon(selectedIcon);
boardArray.get(0).selected = true;
}else{
boardArray.get(0).selected = false;
buttons[0].setIcon(boardArray.get(0).cardImage);
}
}
if(e.getSource() == cardTwo) {
if(boardArray.get(1).selected == false) {
getPath(1);
buttons[1].setIcon(selectedIcon);
boardArray.get(1).selected = true;
}else{
boardArray.get(1).selected = false;
buttons[1].setIcon(boardArray.get(1).cardImage);
}
}
if(e.getSource() == cardThree) {
if(boardArray.get(2).selected == false) {
getPath(2);
buttons[2].setIcon(selectedIcon);
boardArray.get(2).selected = true;
}else{
boardArray.get(2).selected = false;
buttons[2].setIcon(boardArray.get(2).cardImage);
}
}
if(e.getSource() == cardFour) {
if(boardArray.get(3).selected == false) {
getPath(3);
buttons[3].setIcon(selectedIcon);
boardArray.get(3).selected = true;
}else{
boardArray.get(3).selected = false;
buttons[3].setIcon(boardArray.get(3).cardImage);
}
}
if(e.getSource() == cardFive) {
if(boardArray.get(4).selected == false) {
getPath(4);
buttons[4].setIcon(selectedIcon);
boardArray.get(4).selected = true;
}else{
boardArray.get(4).selected = false;
buttons[4].setIcon(boardArray.get(4).cardImage);
}
}
if(e.getSource() == cardSix) {
if(boardArray.get(5).selected == false) {
getPath(5);
buttons[5].setIcon(selectedIcon);
boardArray.get(5).selected = true;
}else{
boardArray.get(5).selected = false;
buttons[5].setIcon(boardArray.get(5).cardImage);
}
}
if(e.getSource() == cardSeven) {
if(boardArray.get(6).selected == false) {
getPath(6);
buttons[6].setIcon(selectedIcon);
boardArray.get(6).selected = true;
}else{
boardArray.get(6).selected = false;
buttons[6].setIcon(boardArray.get(6).cardImage);
}
}
if(e.getSource() == replace) {
checkWin();
}
if(e.getSource() == reset) {
System.out.println("Feature In Progress. Exit game to reset.");
}
}
int total;
int buttonsSelected = 0;
public void checkWin() {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
int pointValue = boardArray.get(i).pointValue();
total = total + pointValue;
buttonsSelected++;
}
}
if((buttonsSelected == 3 && total == 36) || (buttonsSelected == 2 && total == 11)) {
for(int i = 0; i <= 6; i++) {
if(boardArray.get(i).selected == true) {
boardArray.set(i, deck.nextCard());
buttons[i].setIcon(boardArray.get(i).cardImage);
deckCount--;
cardsLeft.setText("Cards left:" + deckCount);
}
}
}
total = 0;
buttonsSelected = 0;
}
}
import javax.swing.ImageIcon;
/**
* Card.java
*
* <code>Card</code> represents a playing card.
*/
public class Card {
/**
* String value that holds the suit of the card
*/
private String suit;
/**
* String value that holds the rank of the card
*/
private String rank;
/**
* int value that holds the point value.
*/
private int pointValue;
/**
* Creates a new <code>Card</code> instance.
*
* #param cardRank
* a <code>String</code> value containing the rank of the card
* #param cardSuit
* a <code>String</code> value containing the suit of the card
* #param cardPointValue
* an <code>int</code> value containing the point value of the
* card
*/
ImageIcon cardImage;
Card card;
Boolean selected = false;
int picNumber = 1;
public Card(String cardRank, String cardSuit, int cardPointValue, Boolean selected) {
// initializes a new Card with the given rank, suit, and point value
rank = cardRank;
suit = cardSuit;
pointValue = cardPointValue;
selected = false;
String pointString = Integer.toString(pointValue);
String path = "/Users/AlecR/Documents/workspace/Elevens Lab Midyear Exam/src/";
if (cardPointValue >= 2 && cardPointValue <= 10) {
String cardImageString = path + pointString + cardSuit + ".GIF";
cardImage = new ImageIcon(cardImageString);
}
if (cardPointValue == 1) {
}
switch (pointValue) {
case 1:
cardImage = new ImageIcon(path + "ace" + cardSuit + ".GIF");
break;
case 11:
cardImage = new ImageIcon(path + "jack" + cardSuit + ".GIF");
break;
case 12:
cardImage = new ImageIcon(path + "queen" + cardSuit + ".GIF");
break;
case 13:
cardImage = new ImageIcon(path + "king" + cardSuit + ".GIF");
break;
}
}
public String getCardImage() {
return cardImage.toString();
}
/**
* Accesses this <code>Card's</code> suit.
*
* #return this <code>Card's</code> suit.
*/
public String suit() {
return suit;
}
/**
* Accesses this <code>Card's</code> rank.
*
* #return this <code>Card's</code> rank.
*/
public String rank() {
return rank;
}
/**
* Accesses this <code>Card's</code> point value.
*
* #return this <code>Card's</code> point value.
*/
public int pointValue() {
return pointValue;
}
/**
* Compare this card with the argument.
*
* #param otherCard
* the other card to compare to this
* #return true if the rank, suit, and point value of this card are equal to
* those of the argument; false otherwise.
*/
public boolean matches(Card otherCard) {
return otherCard.suit().equals(this.suit())
&& otherCard.rank().equals(this.rank())
&& otherCard.pointValue() == this.pointValue();
}
/**
* Converts the rank, suit, and point value into a string in the format
* "[Rank] of [Suit] (point value = [PointValue])". This provides a useful
* way of printing the contents of a <code>Deck</code> in an easily readable
* format or performing other similar functions.
*
* #return a <code>String</code> containing the rank, suit, and point value
* of the card.
*/
#Override
public String toString() {
return rank + " of " + suit + " (point value = " + pointValue + ")";
}
}
When it resets, it is basically same as the state when you start a new game.
When starting a new game:
1) Create deck
2) Shuffle deck
3) Draw images(cards) or reset the image in swing
So when you reset, basically you repeat the same process as above.
You can have something like this:
public static void startNewGame() //use this for reset
{
ArrayList<Card> deck = createNewDeck();
ShuffleCards(deck);
ResetImages(deck); //reset card images
ResetComponents(); //reset all buttons/display to initial state
}
Something like this:
board.this.setVisible(false);
board.this.dispose();
new Board();
You can assign board = new Board(); but you need to make it static in the main class.
The best way is to make it using
public class DeckTester {
.
.
private static Board board;
public static void newBoard(){
board = new Board();
}
Then, refresh what you need.
All you have to do to restart is redefine the attributes as you would at the beginning so if you populate a deck and shuffle it at startup, you should so the same at restart. Try using a function for both scenarios, I'll give you a generic example.
public void setup() {
populate() // populate deck
shuffle() // and shuffle it
// anything else like ...
score = 0;
}

Setting instance Variable, before creating an object

So i got this program which sets subject, and grades it.
now i got this piece of code:
package ectsmonitor;
import java.util.Scanner;
import java.util.stream.IntStream;
/**
*
* #author JasperF
*/
public class ECTSMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak = new String[aantalvakken];
private Scanner input = new Scanner(System.in);
private int[] ECTS = new int[aantalvakken];
private double[] Cijfer = new double[aantalvakken];
private int totaalECTS;
/**
* #param args the command line arguments
*/
/**
* Asks for amount of Subjects, and sets instance variable for size of
* Arrays
*/
public void setSubjects() {
//System.out.println("Hoeveel vakken heb je?");
//aantalvakken = input.nextInt();
System.out.println(vak.length);
for (int x = 0; x < getAantalvakken(); x++) {
System.out.println("Voer de naam in van je vak!");
vak[x] = input.next();
System.out.println("Voer het aantal punten in voor " + vak[x]);
ECTS[x] = input.nextInt();
System.out.println("Vak Toegevoegd!!");
}
}
public void setCijfer() {
for (int x = 0; x < vak.length; x++) {
System.out.println("Wat is je Cijfer voor " + vak[x] + "?");
Cijfer[x] = input.nextDouble();
System.out.println("Voor het vak " + vak[x] + "heb je als cijfer ingevuld " + Cijfer[x]);
}
}
public void Checkscore() {
for (int x = 0; x < vak.length; x++) {
if (Cijfer[x] >= voldoende) {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: " + ECTS[x]);
} else {
System.out.println("vak:" + vak[x] + "\t\t\t\t Cijfer: " + Cijfer[x] + "ECTS behaald: 0");
}
}
}
public void BAS() {
totaalECTS = IntStream.of(ECTS).sum();
if (totaalECTS < (totaalECTS * (5 / 6))) {
System.out.println("PAS OP!!: Je ligt op schema voor een BAS!");
} else {
System.out.println("Gefeliciteerd!!: Je bent op weg naar je Propodeuse!!");
}
}
/**
* #return the aantalvakken
*/
public int getAantalvakken() {
return aantalvakken;
}
/**
* #param aantalvakken the aantalvakken to set
*/
public void setAantalvakken(int aantalvakken) {
this.aantalvakken = aantalvakken;
}
}
and i got this piece of code to run it:
public class Run {
/**
*
* #author JasperF
* #param args
*/
public static void main(String[] args) {
ECTSMonitor mon = new ECTSMonitor();
mon.setSubjects();
mon.setCijfer();
mon.Checkscore();
mon.BAS();
}
}
now in the first code, the lenght of the arrays is set by the variable 'aantalvakken',
but when i run my program, and print the lenght of te array it says 0.
how can i set the variable aantalvakken to set the array length
Pass aantalvakken value to constructor. And create ArrayList's depends on aantalvakken at constructor.
public class ECSTMonitor {
private int aantalvakken;
private final double voldoende = 5.5;
private String[] vak;
private Scanner input = new Scanner(System.in);
private int[] ECTS;
private double[] Cijfer;
private int totaalECTS;
public ECSTMonitor(int aantalvakken) {
this.aantalvakken = aantalvakken;
vak = new String[aantalvakken];
ECTS = new int[aantalvakken];
Cijfer = new double[aantalvakken];
}
private int aantalvakken;
is not initialized and therefore 0 by default.
try using static variables like below, initialize the variable(aantalvakken) how much array length you want.
public static final int aantalvakken;
or
public static final int aantalvakken=10;

Issues with toString and Inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have I am having trouble figuring out an issue I have with a toString method. toString () must be changed so that it prints all the relevant information about the Player (and collection of
Items). Subclasses should overwrite the superclass toString (), but still use the toString ()
from the super class implementation when this reduces code duplication.
How do I go about doing this?
Player class:
import java.util.HashMap;
public class Player extends Character {
private String name;
private String type;
public static HashMap<String, Item> backpack;
private int maxCarryingCapacity;
/**Constructor
* Creates a player with health 100, an empty backpack
* and max carrying capacity 100
*
* #param nick the players name
* #param type the players type
* #param minDamage players minimum damage
* #param maxDamage players maximum damage
*/
public Player(String name, String type, int minDamage, int maxDamage) {
super(name, minDamage, maxDamage);
setName(name);
setType(type);
health = 100;
gold = 100;
backpack = new HashMap<String, Item>();
maxCarryingCapacity = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
/**
* Use an item in backpack
* #param itemName
* #return true if item is used, and false
* if there's no item by that name in the backpack
*/
public boolean useItem(String itemName) {
Item item = findItem(itemName);
if(item != null) {
System.out.println(name + " " + item.getAction() + " " + item.getName());
return true;
} else {
return false;
}
}
public boolean equipItem(String itemToEquip) {
Item item = findItem(itemToEquip);
if (item != null) {
this.minDamage = this.minDamage + item.getBonus();
return true;
} else {
return false;
}
}
/**
* Adds item to players inventory. An
* item can only be bought if the total weight does not
* exceed the players carrying capacity
* #param item
* #return true if the item is bought
*/
public boolean addItem(Item item) {
int totalWeight = totalWeight() + item.getWeight();
if(totalWeight <= maxCarryingCapacity){
backpack.put(item.getName(), item);
return true;
} else {
return false;
}
}
/**
* Find item in backpack
*
* #param name of item
* #return item, or null if item is not int the backpack
*/
public Item findItem(String itemName) {
return backpack.get(itemName);
}
/**
* Removes item from player's backpack and
* add item value to player's gold
*
* #param name of item to sell
* #return true if successful
*/
public boolean sellItem(String itemToSell) {
Item item = findItem(itemToSell);
if(item != null) {
gold += item.getValue();
backpack.remove(item.getName());
return true;
} else {
return false;
}
}
/**
* #return true if the player is alive
*/
public boolean isAlive() {
if(health > 0 && health <= 100) {
return true;
} else return false;
}
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
/**
* #return the players type
*/
public String getType() {
return type;
}
/**Sets the players type
* Valid types: Mage, Ranger, Warrior, Rogue
* #param newType
*/
public void setType(String newType) {
newType = newType.toLowerCase().trim();
if(newType.equals("mage") || newType.equals("ranger") || newType.equals("warrior") || newType.equals("rogue")){
this.type = newType;
} else {
this.type = "Unspecified";
}
}
/**
* #param item
* #return current carrying weight
*/
private int totalWeight() {
int tempWeight = 0;
for(Item itemInBackpack : backpack.values()) {
tempWeight += itemInBackpack.getWeight();
}
return tempWeight;
}
public int attack(Monster currentEnemy) {
int damage = Utils.random(minDamage, maxDamage+1);
currentEnemy.changeHealth(-damage);
return damage;
}
}
The Character superclass (abstract class):
abstract class Character
{
public String name;
public static int health;
public int gold;
public int minDamage;
public int maxDamage;
public Character(String name, int minDamage, int maxDamage) {
setName(name);
health = 100;
gold = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
public Character () {
}
/**
* Changes the character health
* The health can not be less the 0 or "less than or euqal to" 100.
* #param healthPoints
*/
public void changeHealth(int healthPoints) {
int temp = health + healthPoints;
if(temp > 100) {
health = 100;
} else if (temp <= 0) {
health = 0;
} else {
health = temp;
}
}
/**
* #return true if the character is alive
*/
public boolean isDead() {
if(health > 0 && health <= 100) {
return false;
} else return true;
}
/**
* #return the characters name
*/
public String getName() {
return name;
}
/**Set to Unspecified if the string is empty
* #param name
*/
public void setName(String name) {
this.name = Utils.checkString(name);
}
/**
* #return the characters health
*/
public static int getHealth() {
return health;
}
/**
* Get minimum damage
* #return minimum damage
*/
public int getMinDamage() {
return minDamage;
}
/**
* Set minimum damage, if minDamage >= 5, minDamage is otherwise set to 5
* #param minimum Damage
*/
public void setMinDamage(int minDamage) {
this.minDamage = minDamage >= 5 ? minDamage : 5;
}
/**
* Get maximum damage
* #return maximum damage
*/
public int getMaxDamage() {
return maxDamage;
}
/**
* Set maximum damage, if maxDamage <= minDamage, maxDamage is set to minDamage +5
* #param maximum damage
*/
public void setMaxDamage(int maxDamage) {
this.maxDamage = maxDamage <= minDamage ? minDamage+5 : maxDamage;
}
/**
* Get money
* #return amount of money
*/
public int getGold() {
return gold;
}
/**
* Set money
* #param amount of money
*/
public void setGold(int gold) {
this.gold = Utils.checkNegativeInt(gold);
}
}
In general, given two classes, A and B and if class B extends A then B has all of the properties of A plus some of its own. Therefore, when you implement B's toString() method, you should do this:
#Override
public String toString() {
String newStuff = // description of the new variables
return super.toString() + newStuff;
// Now describe the elements of B that aren't included in A
}
However, your implementation doesn't give a basic toString() method for Character so calling super.toString() is equivalent to calling Object.toString(). Therefore you should first implement toString for your Character abstract class.
for example, you could do:
public String toString() {
return "Name: " + name + "\nHealth: " ... all the attributes
}
There is a lot of redundancy in your code though. First of all, both your Character class and your Player class have the same name variable, which goes against the point of inheritance. In fact, you never even use Player's name variable.
also, there is no point in creating getter/setter methods in Character if all the variables are declared public anyways. It is better to make them private and use getter/setters though.
Your abstract superclass has name and health, but not type or backpack. (I just noticed, thanks to user2573153's answer, that you also have name in your Player class; I don't think you want that.)
I think the first thing you want to do is to answer this question: Suppose you create a new subclass, and you don't override toString(), and then an object gets printed out. What would you want to see printed out?
Maybe you want the name and health printed out. So you can declare this in your abstract Character class (which I think shouldn't be called Character because java.lang already has a Character):
#Override
public String toString() {
String string = "Name: " + name + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
return string;
}
Then, if you wanted toString() in Player or Monster to add something to the end of that, it would be pretty easy:
#Override
public String toString() {
String string = super.toString(); // here's where you call the superclass version
string += "\n Type: " + type;
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
In your actual code, however, you want the Type information inserted in the middle of the string that the superclass toString() would return. That makes things tougher. I can think of two ways to handle it. One would be to use some string manipulation methods to search for \n and insert the "Type" string in there. But I think it's better to split the string into two methods. You can put these in your Character class:
protected String nameString() {
return "Name: " + name;
}
protected String healthString() {
if(isAlive()) {
return "Is alive with health: " + health;
} else {
return "Is dead.";
}
}
Now, your toString() in Character might look like
#Override
public String toString() {
return nameString() + "\n" + healthString();
}
and in Player:
#Override
public String toString() {
return nameString() + " Type: " + type + "\n" + healthString();
}
and you still get to avoid duplicated code. (You don't need to say super.nameString() because your subclass will automatically inherit it and you don't plan to override it.)
Superclass methods aren't automatically called. When you override toString() in Player and you call toString() on an instance of Player the only code that gets run is Player's toString().
If you want to include the toString() of Character in your toString() of Player you need to make that explicit by calling super.toString() in Player's toString().
Your Player implementation of toString() could be amended to include my recommendation as follows:
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return super.toString() + string;
}
The salient part of this is changing:
return string;
To:
return super.toString() + string;

Categories