Create a recursive algorithm for multiplication with no parameters - java

When calculating the rank, the number of consecutive Trails of the same type will have increasingly higher rankings. For example, one Trail of type "ice" has a ranking of 4. If there is another ice Trail immediately following it, that second one will have a ranking of 8 (2 *4). If there is a third ice Trail in that sequence, it will have a ranking of 12 (3 * 4).The overall rank of the slope is the sum of all its trails' rankings and this value must be assigned to the instance variable called ranking.
Trail is an array type. So, an example is [3, 3, 3, 3] so the overall rank should be 30. I am trying to create a recursive algorithm.
public int calculateRank () {
for (int i = 0; i < count; i++) {
if (trail[i].equals(0)) {
ranking = 0;
} else if (trail[i + 1] == trail[i]) {
ranking = calculateRank() * trail[i];
}
ranking += ranking;
}
return ranking;
}
Trail class
public class Trail {
private String ID;
private String type;
private int rank;
public Trail (String ID, String type) {
this.ID = ID;
this.type = type;
if (type == "ice") {
rank = 4;
} else if (type == "trees") {
rank = 3;
} else if (type == "rocks") {
rank = 2;
} else if (type == "slalom") {
rank = 1;
} else {
rank = 0;
}
}
public int getRank () {
return rank;
}
public void setRank (int newRank) {
this.rank = newRank;
}
public String getType () {
return type;
}
public void setType (String newType) {
this.type = newType;
}
public String getID () {
return ID;
}
public void setID (String newID) {
this.ID = newID;
}
public String toString () {
String s = "";
s += this.rank;
return s;
}
}
This is what I had written however a. I don't fully understand the code I wrote and b. It results in a compilation error.

Related

A* algorithm completes but returns suboptimal path

The algorithm:
Uses a PQ that supports change priority operations.
Assume all the ADTs work correctly.
Example problem: Find the shortest path of operations to get from integer x to integer y using the following operations and weights; add/subtract 1 : 1, multiply/divide by 2 : 5, square : 10.
Tested against other types of graphs and inputs, sometimes it gets the shortest path, sometimes it gets a suboptimal, sometimes it times out.
import java.util.*;
/**
* Represents a graph of vertices.
*/
public interface AStarGraph<Vertex> {
List<WeightedEdge<Vertex>> neighbors(Vertex v);
double estimatedDistanceToGoal(Vertex s, Vertex goal);
}
public interface ShortestPathsSolver<Vertex> {
SolverOutcome outcome();
List<Vertex> solution();
double solutionWeight();
int numStatesExplored();
double explorationTime();
}
public interface ExtrinsicMinPQ<T> {
/* Inserts an item with the given priority value. */
void add(T item, double priority);
/* Returns true if the PQ contains the given item. */
boolean contains(T item);
/* Returns the minimum item. */
T getSmallest();
/* Removes and returns the minimum item. */
T removeSmallest();
/* Changes the priority of the given item. Behavior undefined if the item doesn't exist. */
void changePriority(T item, double priority);
/* Returns the number of itemToPriority in the PQ. */
int size();
}
public enum SolverOutcome {
SOLVED, TIMEOUT, UNSOLVABLE
}
public class ArrayHeapMinPQ<T> implements ExtrinsicMinPQ<T> {
private ArrayList<PriorityNode> heap;
int count;
private HashMap<T, PriorityNode> items;
public ArrayHeapMinPQ() {
heap = new ArrayList<>();
heap.add(0, new PriorityNode(null, Double.NEGATIVE_INFINITY));
count = 0; // For convenient math
items = new HashMap<>();
}
#Override
public void add(T item, double priority) {
if(contains(item)){
throw new IllegalArgumentException();
}
PriorityNode pn = new PriorityNode(item, priority);
if(count == 0){
heap.add(1, pn);
count++;
}else{
heap.add(count+1, pn);
swim(count+1);
count++;
}
items.put(item, pn);
}
private void swap(int i, int j){
Collections.swap(heap, i, j);
}
private void swim(int i){
while(i > 1){
PriorityNode cur = heap.get(i);
if((cur.compareTo(heap.get(i/2)) >= 0)){
break;
}
swap(i, i/2);
i = i/2;
}
}
private void sink(int k){
while (2*k <= size()-1) {
if(2*k+1 <= size()-1) {
if (heap.get(2 * k).compareTo(heap.get(2 * k + 1)) < 0) {
if (heap.get(k).compareTo(heap.get(2 * k)) > 0) {
swap(k, 2 * k);
k = 2 * k;
continue;
}
} else if(heap.get(k).compareTo(heap.get(2*k+1)) > 0){
swap(2*k+1, k);
k = 2*k +1;
continue;}
}
else if (heap.get(k).compareTo(heap.get(2 * k)) > 0) {
swap(k, 2 * k);
k = 2 * k;
continue;}
break;
}
}
#Override
public int size(){
return heap.size();
}
public PriorityNode getRoot(){
return heap.get(1);
}
#Override
public boolean contains(T item) {
return items.containsKey(item);}
#Override
public T getSmallest() {
if(heap.size() == 0){
throw new NoSuchElementException();
}
return getRoot().getItem();
}
#Override
public T removeSmallest() {
if(heap.size() == 1){
throw new NoSuchElementException();
}
T item = heap.get(1).item;
swap(1, size()-1);
heap.remove(size()-1);
if(size() > 1){
sink(1);
}
items.remove(item);
count--;
return item;
}
public boolean isEmpty(){
return heap.size() == 1;
}
public int getCount() {
return count;
}
#Override
public void changePriority(T T, double priority) {
if(heap.size() == 0){
throw new NoSuchElementException();
}
PriorityNode tochange = items.get(T);
double prioritysearch = tochange.getPriority();
double currprior = getRoot().getPriority();
int left = 0;
int right = 0;
if((prioritysearch != currprior)){
if (currprior > prioritysearch){
add(T, priority);
return;
}
left = heapTraverse(prioritysearch, tochange, 2);
right = heapTraverse(prioritysearch, tochange, 3);
}
if(left == -1 && right == -1){
throw new NoSuchElementException();
}
else if(left > 0){
PriorityNode toChange = heap.get(left);
toChange.setPriority(priority);
if(priority < heap.get(left/2).getPriority()){
swim(left);
}else
sink(left);
}
else {
PriorityNode toChange = heap.get(right);
toChange.setPriority(priority);
if (priority < heap.get(right / 2).getPriority()) {
swim(right);
} else
sink(right);
}
}
private int heapTraverse(double priority, PriorityNode node, int index){
if(index > heap.size()-1){
return -1;
}
PriorityNode curr = heap.get(index);
double currprior = curr.getPriority();
if(currprior == priority && node.equals(curr)){
return index;
} else if(currprior > priority){
return -1;
}else{
if(heapTraverse(priority, node, index*2) == -1){
return heapTraverse(priority, node, index*2 +1);}
else {return heapTraverse(priority, node, index*2);}
}
}
private class PriorityNode implements Comparable<PriorityNode> {
private T item;
private double priority;
PriorityNode(T e, double p) {
this.item = e;
this.priority = p;
}
T getItem() {
return item;
}
double getPriority() {
return priority;
}
void setPriority(double priority) {
this.priority = priority;
}
#Override
public int compareTo(PriorityNode other) {
if (other == null) {
return -1;
}
return Double.compare(this.getPriority(), other.getPriority());
}
#Override
public boolean equals(Object o) {
if( o == null) {
throw new NullPointerException();
}
if (o.getClass() != this.getClass()) {
return false;
} else {
return ((PriorityNode) o).getItem().equals(getItem());
}
}
#Override
public int hashCode() {
return item.hashCode();
}
}
public class WeightedEdge<Vertex> {
private Vertex v;
private Vertex w;
private double weight;
public WeightedEdge(Vertex v, Vertex w, double weight) {
this.v = v;
this.w = w;
this.weight = weight;
}
public Vertex from() {
return v;
}
public Vertex to() {
return w;
}
public double weight() {
return weight;
}
}
public class SolutionPrinter {
/** Summarizes the result of the search made by this solver without actually
* printing the solution itself (if any).
*/
public static <Vertex> void summarizeOutcome(ShortestPathsSolver<Vertex> solver) {
summarizeSolution(solver, "", false);
}
/** Summarizes the result of the search made by this solver and also
* prints each vertex of the solution, connected by the given delimiter,
* e.g. delimiter = "," would return all states separated by commas.
*/
public static <Vertex> void summarizeSolution(ShortestPathsSolver<Vertex> solver,
String delimiter) {
summarizeSolution(solver, delimiter, true);
}
private static <Vertex> String solutionString(ShortestPathsSolver<Vertex> solver,
String delimiter) {
List<String> solutionVertices = new ArrayList<>();
for (Vertex v : solver.solution()) {
solutionVertices.add(v.toString());
}
return String.join(delimiter, solutionVertices);
}
private static <Vertex> void summarizeSolution(ShortestPathsSolver<Vertex> solver,
String delimiter, boolean printSolution) {
System.out.println("Total states explored in " + solver.explorationTime()
+ "s: " + solver.numStatesExplored());
if (solver.outcome() == SolverOutcome.SOLVED) {
List<Vertex> solution = solver.solution();
System.out.println("Search was successful.");
System.out.println("Solution was of length " + solution.size()
+ ", and had total weight " + solver.solutionWeight() + ":");
if (printSolution) {
System.out.println(solutionString(solver, delimiter));
}
} else if (solver.outcome() == SolverOutcome.TIMEOUT) {
System.out.println("Search timed out, considered " + solver.numStatesExplored()
+ " vertices before timing out.");
} else { // (solver.outcome() == SolverOutcome.UNSOLVABLE)
System.out.println("Search determined that the goal is unreachable from source.");
}
}
}
public class AStarSolver implements ShortestPathsSolver {
private final AStarGraph<Vertex> graph;
private Vertex source;
private Vertex dest;
private SolverOutcome result;
private HashMap<Vertex, Double> distTo = new HashMap<>();
private ArrayHeapMinPQ<Vertex> fringe = new ArrayHeapMinPQ<>();
private HashMap<Vertex, WeightedEdge<Vertex>> edgeTo = new HashMap<>(); // answers the question which vertex to ge to this vertex
private double solutionweight;
private List<Vertex> solution;
private ArrayList<Vertex> marked = new ArrayList<>();
private double timetosolve;
private int numofstates = 0;
public AStarSolver(AStarGraph<Vertex> input, Vertex start, Vertex end, double timeout ){
graph = input;
source = start;
dest = end;
if(start.equals(end)){
solutionweight = 0;
solution = List.of(start);
result = SolverOutcome.SOLVED;
numofstates = 0;
timetosolve = 0;
return;
}
fringe.add(start, 0.0);
distTo.put(start, 0.0);
while (!fringe.isEmpty()) {
Vertex src = fringe.removeSmallest();
numofstates++;
marked.add(src);
List<WeightedEdge<Vertex>> neighbors = graph.neighbors(src);
for(WeightedEdge<Vertex> e: neighbors){
double heur = graph.estimatedDistanceToGoal(e.to(), dest);
if ((heur == Double.POSITIVE_INFINITY || marked.contains(e.to())) && !e.to().equals(dest)) {
continue;
}
double distFr = distTo.get(e.from()) + e.weight();
if(!distTo.containsKey(e.to())){
distTo.put(e.to(), distFr);
}
if (!fringe.contains(e.to())) {
fringe.add(e.to(), distFr + heur);
edgeTo.put(e.to(), e);
}
if (distTo.get(e.to()) > distFr) {
fringe.changePriority(e.to(), heur + distFr);
edgeTo.put(e.to(), e);
distTo.put(e.to(), distFr);
}
if (e.to().equals(dest)) {
solutionweight = distTo.get(e.to());
solution = pathTracer(e);
timetosolve = sw.elapsedTime();
result = SolverOutcome.SOLVED;
return;
}
if (e.to().equals(dest)) {
solutionweight = distTo.get(e.to());
solution = pathTracer(e);
timetosolve = sw.elapsedTime();
result = SolverOutcome.SOLVED;
return;
}
}
if (timeout < sw.elapsedTime()){
result = SolverOutcome.TIMEOUT;
return;
}
}
result = SolverOutcome.UNSOLVABLE;
solution = List.of();
}
private List<Vertex> pathTracer(WeightedEdge<Vertex> e) {
ArrayList<Vertex> path = new ArrayList<>();
path.add(e.to());
path.add(e.from());
while (!e.from().equals(source)) {
e = edgeTo.get(e.from());
path.add(e.from());
}
Collections.reverse(path);
return path;
}
#Override
public SolverOutcome outcome() {
return result;
}
#Override
public List solution() {
return solution;
}
#Override
public double solutionWeight() {
return solutionweight;
}
#Override
public int numStatesExplored() {
return numofstates;
}
#Override
public double explorationTime() {
return timetosolve;
}
public class IntegerHopGraph implements AStarGraph<Integer> {
#Override
public List<WeightedEdge<Integer>> neighbors(Integer v) {
ArrayList<WeightedEdge<Integer>> neighbors = new ArrayList<>();
neighbors.add(new WeightedEdge<>(v, v * v, 10));
neighbors.add(new WeightedEdge<>(v, v * 2, 5));
neighbors.add(new WeightedEdge<>(v, v / 2, 5));
neighbors.add(new WeightedEdge<>(v, v - 1, 1));
neighbors.add(new WeightedEdge<>(v, v + 1, 1));
return neighbors;
}
#Override
public double estimatedDistanceToGoal(Integer s, Integer goal) {
// possibly fun challenge: Try to find an admissible heuristic that
// speeds up your search. This is tough!
return 0;
}
}
public class DemoIntegerHopPuzzleSolution {
public static void main(String[] args) {
int start = 17;
int goal = 111;
IntegerHopGraph ahg = new IntegerHopGraph();
ShortestPathsSolver<Integer> solver = new AStarSolver<>(ahg, start, goal, 10);
SolutionPrinter.summarizeSolution(solver, " => ");
}
}
}
To get from x = 11, to y = 117 the algorithm gives this result:
Total states explored in 0.019s: 110
Search was successful.
Solution was of length 7, and had total weight 19.0:
17 => 16 => 15 => 225 => 224 => 223 => 111
The correct result should is:
Total states explored in 0.018s: 338 <--- may vary.
Search was successful.
Solution was of length 6, and had total weight 18.0:
17 => 16 => 15 => 225 => 112 => 111
Thanks for all the help guys but I figured it out. My algorithm terminates prematurely. It stops when it sees the finish, not when it is on the top of the heap like it should.

Java HashSet is allowing duplicates

I need to create an ID based on a 15x15 matrix values and since it is not possible to create an integer of size 15, I tried the following reasoning to create an ID of type double:
First I create a String with the values of the cells and while I do this, I look for the cell that has a value of 0. When I find I enter a dot "." in the String. Then I convert my String to BigDecilmal and the method I call doubleValue ().
public double generateId() {
String sid = "";
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < matrix[1].length; j++) {
if (matrix[i][j].equals("0")) {
sid += ".";
} else {
sid += matrix[i][j];
}
}
}
System.out.println("ID: " + new BigDecimal(sid).doubleValue());
return new BigDecimal(sid).doubleValue();
}
I checked and the generated IDs are uniques.
Based on this, I tried to implement HashCode() as follows:
#Override
public int hashCode() {
long bits = doubleToLongBits(id);
int hash = (int) (bits ^ (bits >>> 32));
System.out.println("hash: " + hash);
return hash;
}
But my HashSet continues with duplicate values :(
Does anyone have a suggestion about how to do this?
~~>EDIT
Sate class:
public class State {
public double id;
public String[][] matrix;
public State() {
}
public State(String[][] matrix) {
this.matrix = createMatrix(matrix);//is created from a existing matrix
this.id = generateId();
}
#Override
public boolean equals(Object other) {
if ((other == null) || !(other instanceof State)) {
return false;
}
return ((State) other).getId().equals(this.getId()) && ((State) other).getId() == this.getId();
}
#Override
public int hashCode() {
long bits = doubleToLongBits(id);
int hash = (int) (bits ^ (bits >>> 32));
System.out.println("hash: " + hash);
return hash;
}
public String toString() {
return "Hashcode: " + this.hashCode();
}
public Double getId() {
return id;
}
public void setId(Double id) {
this.id = id;
}
public String[][] getMatrix() {
return matrix;
}
public void setMatrix(String[][] matrix) {
this.matrix = matrix;
}
public double generateId() {
String sid = "";
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < matrix[1].length; j++) {
if (matrix[i][j].equals("0")) {
sid += ".";
} else {
sid += matrix[i][j];
}
}
}
System.out.println("ID: " + new BigDecimal(sid).doubleValue());
return new BigDecimal(sid).doubleValue();
}
private String[][] createMatrix(String[][] matriz) {
String[][] copia = new String[matriz[0].length][matriz[1].length];
for (int i = 0; i < copia[0].length; i++) {
for (int j = 0; j < copia[1].length; j++) {
copia[i][j] = matriz[i][j];
}
}
return copia;
}
your problem is in the equals method,
you have to remove the last part:
&& ((State) other).getId() == this.getId();
you are checking if the Boolean has the same reference, but they don't need the reference to be equal, it's enough that there value is equal
I would propose using the built-in methods of the Arrays class to generate a hashCode and test for equality:
#Override
public int hashCode() {
return Arrays.deepHashCode(matrix);
}
#Override
public boolean equals(Object other) {
if ((other == null) || !(other instanceof State)) {
return false;
}
State s = (State)other;
return Arrays.deepEquals(matrix, s.matrix);
}

Comparing an Object's values with compareTo()

I am using a Max-Heap to store objects of type Song. A song has a title and a rating as shown in the Song class. I want the Song object to be compared by rating so that the highest rated songs are displayed first. If songs have the same rating then they should be compared by alphabetical order of title. What I have now is currently outputting it by highest rating, but incorrectly.
Heap:
public class Heap<T extends Comparable<T>> {
private ArrayList<T> heap;
public Heap(){
heap = new ArrayList<T>();
}
public int getPLoc(int i){
return (i - 1) / 2;
}
public int getLCLoc(int i){
return 2 * i + 1;
}
public int getRCLoc(int i){
return 2 * i + 2;
}
public T getNodeAt(int i) {
if(heap.get(i) == null) {
System.out.println("Item does not exist.");
return null;
}else {
return heap.get(i);
}
}
public void addNode(T n) {
heap.add(null);
int index = heap.size() - 1;
while(index > 0 && (getNodeAt(getPLoc(index)).compareTo(n)) < 0) { //Is this correct?
heap.set(index, getNodeAt(getPLoc(index)));
index = getPLoc(index);
}
heap.set(index, n);
}
Song:
public class Song implements Comparable<Song> {
private String title;
private String rating;
public Song(String t, String r) {
title = t;
rating = r;
}
public String getTitle(){
return title;
}
public String getRating(){
return rating;
}
// Need help here adding it to also compare by alphabetical title if songs have same ratings.
public int compareTo(Song s) {
return rating.compareTo(s.getRating());
}
The compareTo() method returns an int with the following values:
negative If thisObject < anotherObject
zero If thisObject == anotherObject
positive If thisObject > anotherObject
Check for value zero, meaning rating is same, then go for title comparison.
Sample Code , can be tweaked
public int compareTo(Song s) {
int val = rating.compareTo(s.getRating());
if(val == 0){
val = title.compareTo(s.getTitle());
}
return val;
}
Solution is to compare the name of the songs if their Rank is equal (and compareTo therefore returns 0) and return the result of the Second compare

Very Basic Java: For-Loop in Java method won't run

I've never asked a question on this before but I'd appreciate any help anyone can provide. I'm currently learning the fundamentals of Java so this is more than likely a very basic problem. When I call this method, nothing seems to happen and I can't figure out why. I could just change it to type void and use system.print but I'd rather not, anyhow here's the code:
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
I think it would be easier if I just showed you guys the whole lot, this is the app that's calling the methods to test them:
public class JukeboxApp {
public static void main(String[] args) {
Song s1 = new Song("Metallica", "The Unforgiven", 1.25, 6.23);
Song s2 = new Song("Test Artist 2", "Test Title 2", 4.00, 3.40);
Song s3 = new Song("Test Artist 3", "Test Title 3", 6.00, 2.50);
Jukebox jb = new Jukebox();
jb.addSong(s1);
jb.addSong(s2);
jb.addSong(s3);
jb.displaySongs();
jb.removeSong("The Unforgiven");
jb.searchSong("Test Title 2");
jb.calcTotal();
}
}
Here is the jukebox class, which I'm sure is full of mistakes:
import java.util.ArrayList;
public class Jukebox {
private String name;
private ArrayList<Song> jSongs;
public Jukebox()
{
name = "Primary Jukebox";
jSongs = new ArrayList<Song>();
}
public String getName()
{
return name;
}
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
public void searchSong(String sTitle)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("The are no songs in the list.");
check = true;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(sTitle) == true ) {
check = true;
System.out.println(jSongs.get(i));
}
}
}
if ( check == false ) {
System.out.println("The searched song could not be found.");
}
}
public String searchArtist(String sArtist)
{
int countMatch = 0;
for (int i = 0; i < jSongs.size(); i++) {
if ( jSongs.get(i).getArtist().equals(sArtist) ) {
countMatch++;
return jSongs.get(i).getTitle();
} else if ( countMatch == 0 ) {
return "The requested artist could not be found.";
}
}
return "If you would like to search for another artist, please enter the corresponding number.";
}
public void addSong(Song s1)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
return;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i) == s1 ) {
check = true;
}
}
}
if ( check == false ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
} else if ( check == true ) {
System.out.println("Your song is already in the list.");
}
}
public void removeSong(String title)
{
boolean check = false;
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(title) ) {
jSongs.remove(i);
check = true;
}
}
System.out.println(check);
}
public void displaySongs()
{
for ( int i = 0; i < jSongs.size(); i++ ) {
System.out.println(jSongs.get(i));
}
}
public Song showMostExpensive()
{
double price = 0.00;
Song mostESong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getPrice() > price ) {
price = jSongs.get(i).getPrice();
mostESong = jSongs.get(i);
}
}
return mostESong;
}
public Song showShortest()
{
double length = 500.00;
Song shortest = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getLength() < length ) {
length = jSongs.get(i).getLength();
shortest = jSongs.get(i);
}
}
return shortest;
}
public Song mostPlayed()
{
int count = 0;
Song mostPSong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getCount() > count ) {
count = jSongs.get(i).getCount();
mostPSong = jSongs.get(i);
}
}
return mostPSong;
}
}
And here is the class that creates the song objects:
public class Song {
private String artist;
private String title;
private double price;
private int playCount;
private double length;
public Song()
{
artist = "unknown";
title = "unknown";
price = 0.00;
length = 0.00;
playCount = 0;
}
public Song(String artist, String title, double price, double length)
{
this.artist = artist;
this.title = title;
this.price = price;
this.length = length;
playCount = 0;
}
public String getArtist()
{
return artist;
}
public String getTitle()
{
return title;
}
public double getPrice()
{
return price;
}
public int getCount()
{
return playCount;
}
public double getLength()
{
return length;
}
public void changePrice(double newPrice)
{
price = newPrice;
}
public void playSong()
{
playCount++;
System.out.println(title + " is now playing." + "\n" + toString());
}
public String toString()
{
return artist + "\n"
+ title + "\n"
+ price + "\n"
+ length;
}
}
Your description makes me think that you are calling your method like so
calcTotal();
instead of actually using the value returned by the method
double total = calcTotal();
System.out.println(total);
Your code seem to be good. Probably the function for addSong could be easier. But the problem is that you're not printing the result of the function calcTotal().

How would I add enumerated type values in an array

Heres the method where I try to add everything. What im trying to do is add up a series of coins, which are named penny,dime...etc. And i gave all of them a value within the enum. But how do I access each of the coins within the array, then add up their values?
public double totalValue(Coin[] coins)
{
double sum = 0;
//computes and returns the monetary value of all the coins in the jar
for(int i = 0; i < coins.length; i++)
{
double coinValue = coins[i].CoinName.getCoinValue();
sum = sum + coins[i];
System.out.println(sum);
}
return sum; //change this!
}
and here is where the values for the enum are defined.
public enum CoinName
{
PENNY(.01), NICKEL(.05), DIME(.10), QUARTER(.25), FIFTY_CENT(.50), DOLLAR(1.0);
private double value;
private double coinValue;
private CoinName(double value)
{
this.coinValue = value;
}
public double getCoinValue()
{
return coinValue;
}
}
///// I have just added my coin class.
import java.util.Random;
public class Coin
{
public static long SEED = System.currentTimeMillis();
public static Random RANDOM = new Random(SEED);
//private instance variables denomination, year, and sideUp: year is an int, denomination is of type CoinName and sideUp is of type CoinSide
private CoinName denomination;
private CoinSide sideUp;
private int year;
public Coin(CoinName denomination,int year)
{
this.denomination = denomination;
this.year = year;
int side = Coin.RANDOM.nextInt(2);
if (side == 0)
{
sideUp = CoinSide.HEADS;
}
else
sideUp = CoinSide.TAILS;
}
//Accessors for denomination, year and sideUp
public CoinName setDenomination()
{
int i = 0;
i = Coin.RANDOM.nextInt(6);
if (i == 0)
{
denomination = CoinName.PENNY;
}
if (i == 1)
{
denomination = CoinName.NICKEL;
}
if (i == 2)
{
denomination = CoinName.DIME;
}
if (i == 3)
{
denomination = CoinName.QUARTER;
}
if (i == 4)
{
denomination = CoinName.FIFTY_CENT;
}
if (i == 5)
{
denomination = CoinName.DOLLAR;
}
return denomination;
}
public CoinName getDenomination()
{
return denomination;
}
public void setSideUp(CoinSide sideUp)
{
sideUp = sideUp;
}
public CoinSide getSideUp()
{
return sideUp;
}
public void setYear(int year)
{
year = RANDOM.nextInt(2013-1873) + 1873;
}
public int getYear()
{
return year;
}
//the standard toString method that prints out a coin in the format “PENNY/1990/HEADS”
public String toString()
{
return denomination + "/" + year + "/" + sideUp;
}
//the standard equals method that checks if two Coin objects are equal – they are equal if the denominations are identical
public boolean equals(Object obj)
{
if (obj instanceof Coin){
Coin d = (Coin)obj;
if (this.getDenomination()==d.getDenomination())
return true;
else
return false;
}
return false;
}
public void toss()
{
//flip the coin
//Use the object RANDOM to generate random numbers
int side = Coin.RANDOM.nextInt(2);
if (side == 0)
{
sideUp = CoinSide.HEADS;
}
else
sideUp = CoinSide.TAILS;
}
}
A Coin has a denomination, which holds the value of the coin. With how you have defined things, to sum the values of an array of coins you have to first get the denomination and then extract the value from it:
for(int i = 0; i < coins.length; i++)
{
CoinName denomination = coins[i].getDenomination();
sum = sum + denomination.getCoinValue();
System.out.println(sum);
}
Note that for this to work the array of coins must be full, with no null values, and each coin must have a denomination.
Assuming that your Coin class has a CoinName property which of type CoinName then you need to change the line
sum = sum + coins[i];
to use the coinValue you get the line before. So change to
sum = sum + coinValue;
or typically this would be
sum += coinValue;
You also have in your Enum two doubles which, one of which is not needed, remove the value

Categories

Resources