illegal start of expression public boolean setTuitionFees;(double fees);{ [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to create a method so I can set the "tuitionFees" and "scholarships" as a double for the profile of the user of the program. I'm unsure if I'm even setting this up right.
import java.util.Scanner;
/**
StudentInvoice.java
Defines StudentInvoice objects
#author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees, double scholarship){
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name){
if(name.length() == 0)
{
return false;
}
else
{
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
public boolean setTuitionFees(double fees){
if(fees < 0.0) {
return false;
}
else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships (double scholarship){
if(scholarship < 0.0) {
return false;
}
else {
Scholarships = scholarship;
return true;
}
}
}
}
My class with the interactions:
public class StudentInvoiceApp {
public static void main (String[] args) {
StudentInvoice Evan = new StudentInvoice("Evan Fravert");
Evan.setName("Evan Fravert");
Evan.setNumber(01234);
Evan.setTuitionFees(0.00);
Evan.setScholarship(0.00);
System.out.print(Evan);
}
}

Upon trying to edit your post, I discovered you had a missing brace after setStudentNumber. The corrected code with proper formatting is below. In any programming language, formatting your code is important to understanding its meaning. People write entire books on how to format code, and for good reason. With good formatting, you likely would have noticed the missing brace.
Searching for "How to format Java code" yields several useful conventions, including documents from Oracle about how they format their Java code. When in doubt, most IDE's provide shortcuts to format code as well. In Eclipse, it's Ctrl+Shift+F, and in NetBeans, it's Alt+Shift+F.
import java.util.Scanner;
/**
* StudentInvoice.java Defines StudentInvoice objects
*
* #author: Evan Fravert
*/
public class StudentInvoice {
// declare instance variables here
// constructor
// methods
// toString method (for String output)
private String studentName;
private String studentNumber;
private double tuitionFees;
private double scholarships;
public String toString() {
String output = "Name: " + studentName + "\n";
output += "Student ID Number: " + studentNumber + "\n";
output += "Tuition & Fees: " + tuitionFees + "\n";
output += "Scholarship: " + scholarships + "\n";
return output;
}
public StudentInvoice(String name, String number, double fees,
double scholarship) {
studentName = name;
studentNumber = number;
tuitionFees = fees;
scholarships = scholarship;
}
public boolean setStudentName(String name) {
if (name.length() == 0) {
return false;
} else {
studentName = name;
return true;
}
}
public boolean setStudentNumber(String number) {
if (number.length() == 0) {
return false;
} else {
studentNumber = number;
return true;
}
}
public boolean setTuitionFees(double fees) {
if (fees < 0.0) {
return false;
} else {
tuitionFees = fees;
return true;
}
}
public boolean setScholarships(double scholarship) {
if (scholarship < 0.0) {
return false;
} else {
scholarships = scholarship;
return true;
}
}
}

change your setStudentNumber method to this
public boolean setStudentNumber(String number){
if(number.length() == 0)
{
return false;
}
else
{
studentNumber = number;
return true;
}
}
you were missing an closing brace for else

Related

Return a string in boolean method

I have a boolean method as following below
public boolean validID(String personalNumber) { .... }
I wanna to print out a string "is valid" or "is not valid" dependent on if the boolean true or false.
the problem is how can I print out string in a boolean method. The code below return always false even if the if statment is true.
if (sum % 10 == 0) {
return Boolean.parseBoolean("is valid");
} else {
return false;
}
You have only two choices :
a boolean method :
public boolean validID(String personalNumber) {
// ... code to compute 'sum'
return sum % 10 == 0;
}
a String method :
public String validID(String personalNumber) {
// ... code to compute 'sum'
if (sum % 10 == 0) {
return personalNumber + " is valid";
} else {
return personalNumber + " is not valid";
}
}
Or a choice that combine both, the String one that calls the boolean one :
public boolean isValidId(String personalNumber) {
// ... code to compute 'sum'
return sum % 10 == 0;
}
public String validID(String personalNumber) {
if (isValidId(personalNumber)) {
return personalNumber + " is valid";
} else {
return personalNumber + " is not valid";
}
}
I'd suggest to take the boolean one, the better is to let the method find the validity of the personalNumber and let the code that calls it handle the result to print a message, because you may this method again and this time you'll need the boolean result to handle it differently
String id = "fs6d7f6sd";
if(this.validID(id))
System.out.println("ID is valid");
else
System.out.println("ID is not valid");
I recommend to use bean Result.
Check my code.
class Result {
private boolean value;
private String message;
public Result(boolean value, String message) {
this.value = value;
this.message = message;
}
// getter & setter
}
public Result validID(String number) {
// ... code to compute 'sum'
return sum % 10 == 0 ?
new Result(true, "valid") :
new Result(false, "invalid");
}

How to use set methods on obj. reference to change values

package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonalds", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
//I would like the code to go here, in-between the toString and the equals comparison.
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by restaurant 1 is: $");
System.out.println(r1.getAverageTaxes());
System.out.print("The avg. annual taxes paid by restaurant 2 is: $");
System.out.println(r2.getAverageTaxes());
System.out.println();
}
}
Hello. I am new-ish to Java and OOP in general, but passable in Python and C. I need to find out how to use the appropriate mutator (setter) methods on Restaurant object reference r2, and change the value of number of people served and the average price per person to the same values in Restaurant object reference r1. I do not want to change the restaurant name.
Restaurant class:
package restaurantclient;
public class Restaurant extends Store {
//Instance Variables
private int peopleServed;
private double averagePrice;
//Constructor with 3 parameters
public Restaurant(String storename, int peopleServed, double averagePrice) {
super(storename);
setPeopleServed(peopleServed);
setAveragePrice(averagePrice);
}
//Getters (Accessors)
public int getPeopleServed() {
return peopleServed;
}
public double getAveragePrice() {
return averagePrice;
}
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
//toString Method [Must Override]
#Override
public String toString() {
String information = "Store name: " + (super.getName());
information += "\n" + "The number of people served: " + peopleServed;
information += "\n" + "The average price per person: $" + averagePrice;
return information;
}
//Equals Method
public boolean equals (Restaurant restaurant) {
if (this == restaurant)
return true;
if (restaurant == null)
return false;
if (getClass() != restaurant.getClass())
return false;
Restaurant other = (Restaurant) restaurant;
if (super.getName() == null) {
if (other.getName() != null)
return false;
} else if (super.getName().equals(other.getName()))
return false;
if (peopleServed == -1) {
if (other.peopleServed != -1)
return false;
} else if (peopleServed == (other.peopleServed))
return false;
if (averagePrice == -1) {
if (other.averagePrice != -1)
return false;
else if (averagePrice == (other.averagePrice))
return false;
}
return false;
}
public double getAverageTaxes() {
double total;
total = this.getPeopleServed() * this.getAveragePrice()
* super.CA_TAX_RATE;
return total;
}
}
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
You already have defined the setter methods on the class -
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
And, as for your question -
to use the appropriate mutator (setter) methods on Restaurant object reference r2, and change the value of number of people served and the average price per person to the same values in Restaurant object reference r1
First, retrieve the values for the r1 object using the getter methods, then pass those values in for the setter methods on the r2 object. As an example -
int peopleToSet = r1.getPeopleServed();
r2.setPeopleServed(peopleToSet);
or, more concisely -
r2.setPeopleServed(r1.getPeopleServed());

Converting strings to dates and comparing in ArrayList Java

I'm completely brand new to programming and Java so excuse any stupid mistakes and really awful code (I have no clue how to order/format). I've been given a task to make an inventory of videos which has three functions: list, rent and check. I have an ArrayList which holds the current inventory of videos available. Under the check function I want to be able to convert the returndate string into a Date and then compare this to today's date. If the returndate and today's date are equal I want to return a message saying: "Video is due today" and if the returndate has passed (is earlier than today's date) I want to return a message saying "Video is overdue".
I've been researching how to convert strings into dates and vice versa and have been trying all day to use this and more to try and make it work but I just can't seem to get it to work. I know there are many similar questions like this that have been asked and answered but I've tried following them and it's not working. Any help would be really appreciated. As I said before I'm a total newbie so excuse any stupidity.
Whole program code:
import java.text.DateFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;
class InventoryRow {
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name, String type, Character availability, String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) throws ParseException {
List<InventoryRow> videos = new ArrayList<InventoryRow>();
videos.add(new InventoryRow("Casablanca", "Old", 'Y', null));
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N', "2015-07-30"));
videos.add(new InventoryRow("2012", "Regular", 'Y', null));
videos.add(new InventoryRow("Ant-Man", "New", 'Y', null));
LocalDate dateReturn = LocalDate.now().plusDays(3);
LocalDate dateToday = LocalDate.now();
Scanner input = new Scanner(System.in);
// Output the prompt
System.out.println("Do you want to list (l), rent (r) or check (c)?");
// Wait for the user to enter a line of text
String line = input.nextLine();
// List, rent and check functions
// List function
if (line.equals("l")) {
// //////////////////////////// Sort function
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
// /////////////////////////// Rent function
} else if (line.equals("r")) {
System.out.println("Which video would you like to rent?");
String line2 = input.nextLine();
// /////////////////////////// Search through ArrayList
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line2.equals(ir.getName()) && ir.getAvailability() == 'Y') {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video available to rent! Would you like to rent this video?");
String line3 = input.nextLine();
if (line3.equals("Yes")) {
System.out.println("You have rented this video until " + dateReturn + ".");
for (InventoryRow ir : videos) {
if (ir != null && line2.equals(ir.getName())) {
ir.setAvailability('N');
ir.setReturndate(dateReturn.toString());
// //////////////// Just to test if this works
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
}
} else {
System.out.println("You have not rented this video.");
}
} else {
System.out.println("Video unavailable to rent.");
}
// /////////////////////////// Check function
} else if (line.equals("c")) {
System.out.println("Which video would you like to check is in the inventory?");
String line4 = input.nextLine();
// /////////////////////////// Search through ArrayList
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line4.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");
for (InventoryRow ir : videos) {
LocalDate returnDate = LocalDate.parse(ir.getReturndate());
if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
System.out.println("Video due for return today.");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
&& returnDate.isBefore(dateToday)) {
System.out.println("Video is overdue!");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
System.out.println("Video is due for return on: " + ir.getReturndate());
}
}
} else {
System.out.println("Video not found. Please see the inventory below.");
Collections.sort(videos, new Comparator<InventoryRow>() {
public int compare(InventoryRow o1, InventoryRow o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (InventoryRow inventory : videos) {
System.out.println(inventory);
}
}
// /////////////////////////// If anything else is entered
} else {
System.out.println("The only options are to list (l), rent (r) or check (c).");
}
}
}
This is the bit that isn't working and I don't know why:
if (foundIt) {
System.out.println("Video found!");
for (InventoryRow ir : videos) {
LocalDate returnDate = LocalDate.parse(ir.getReturndate());
if (line4.equals(ir.getName()) && ir.getAvailability() == 'N' && returnDate.isEqual(dateToday)) {
System.out.println("Video due for return today.");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N'
&& returnDate.isBefore(dateToday)) {
System.out.println("Video is overdue!");
} else if (line4.equals(ir.getName()) && ir.getAvailability() == 'N') {
System.out.println("Video is due for return on: " + ir.getReturndate());
}
}
This is the error message I get:
Exception in thread "main" java.lang.NullPointerException: text
at java.util.Objects.requireNonNull(Objects.java:228)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1846)
at java.time.LocalDate.parse(LocalDate.java:400)
at java.time.LocalDate.parse(LocalDate.java:385)
at InventorySort.main(InventorySort.java:141)
From your example:
// Gets today's date
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
You have return date in string format as below:
videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
"30/07/2015"));
Now the difference between current day and return date:
Date todayDate = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
String currDateStr = dateFormat.format(todayDate);
String returnDateStr = "01/08/2015";
Date returnDate = null;
try {
returnDate = dateFormat.parse(returnDateStr);
todayDate = dateFormat.parse(currDateStr);
}
catch (ParseException e) {
e.printStackTrace();
}
long diffInDays = (todayDate.getTime() - returnDate.getTime()) / (24 * 60 * 60 * 1000);
if (diffInDays == 0) {
System.out.println("Video is due today!");
}
else if (diffInDays > 0) {
System.out.println("Video is overdue :(");
}
else {
System.out.println("Video returned in advance :) ");
}
One thing you can do is instead of trying to covert "dates" is to convert the strings that represent the dates to numbers. The way you do this is by parsing a String to an Integer in this case. For example:
class Example {
public static void main(String[] args) {
String Date = "07/30/2015";
String[] DatesTxt = Date.split("/");
int[] DatesInt = new int[3];
for (int i = 0; i < DatesTxt.length; i++) {
DatesInt[i] = Integer.parseInt(DatesTxt[i]);
}
if (DatesInt[1] < 31) {
System.out.println("And look am comparing dates!");
}
}
}
I hope this helped :).

Need to add two objects together in Java that consist of Feet & Inches

I have an issue that I can't quite wrap my mind around. Maybe someone could help me out.
I have created a DISTANCE class that contains two variables FEET & INCHES. I need to add a Method to that class that adds two separate DISTANCE objects of Feet & Inches.
Here is my class so far:
public class Distance {
static int feet; // 0 - infinity
static int inches; // 0 - infinity
public Distance() { // default constructor
this.feet = 0;
this.inches = 0;
}
public Distance(int ft, int in){ // parametarized constructor
this.feet = ft;
this.inches = in;
System.out.println("constructor w/2 ints : " + feet + ", " + inches);
}
public void setDistance(int ft, int in){
setFeet( ft );
setInches( in );
}
public static int getFeet() {
return (feet);
}
public static void setFeet(int feet) {
Distance.feet = feet;
}
public static int getInches() {
return inches;
}
public static void setInches( int inches) {
Distance.inches = inches;
}
public Distance(Distance d){
//Distance total = d;
d.getDistance();
}
private int getDistance() {
int totalInches;
totalInches = (feet * 12) + inches;
return totalInches;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + feet;
result = prime * result + inches;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Distance other = (Distance) obj;
if (feet != other.feet)
return false;
if (inches != other.inches)
return false;
return true;
}
#Override
public String toString() {
return "Distance [feet=" + feet + ", inches=" + inches + "]";
}
}
The method I am trying to write needs to add to Distance Objects. Here is what I've tried so far: if
public Distance add(Distance d){
Distance total;
total = this.getDistance() + d.getDistance();
return total;
}
Instead of trying to assign an int to a Distance object, use your constructor
public Distance add(Distance d){
Distance total = new Distance(this.feet + d.feet, this.inches + d.inches);
return total;
}
Also, you should probably not declare feet and inches as static variables since whenever you modify it, it changes for all of your Distance objects.
Change from:
static int feet; // 0 - infinity
static int inches; // 0 - infinity
to:
private int feet; // 0 - infinity
private int inches; // 0 - infinity
You are using static variable in the object. Each time you instantiate a Distance object you set all Distance objects to those values.
Distance a = new Distance(1,3);
Distance b = new Distance(3,1);
System.out.println(a.getFeet());
//should return 3
You can do this in your code
public static Distance add(Distance d1,Distance d2){
return new Distance(d1.getFeet() + d2.getFeet(), d1.getInches() + d2.getInces);
}
Your entire code should be changed to the following
public class Distance {
private int feet;
private int inches;
public Distance(int ft, int in){ // parametarized constructor
this.feet = ft;
this.inches = in;
System.out.println("constructor w/2 ints : " + feet + ", " + inches);
}
public int getFeet() {
return feet;
}
public int getInches() {
return inches;
}
public int getDistance() {
return (feet * 12) + inches;
}
public static Distance add(Distance d1,Distance d2){
return new Distance(d1.getFeet() + d2.getFeet(), d1.getInches() + d2.getInces);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + feet;
result = prime * result + inches;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Distance other = (Distance) obj;
if (feet != other.getFeet())
return false;
if (inches != other.getInches())
return false;
return true;
}
#Override
public String toString() {
return "Distance [feet=" + getFeet() + ", inches=" + getInches() + "]";
}
}
You could also do it like this:
public class Distance {
private int feet;
private int inches;
public Distance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
public int getDistanceInInches() {
return feet * 12 + inches;
}
public Distance add(Distance distance) {
return new Distance(this.feet + distance.feet, this.inches + distance.inches);
}
#Override
public String toString() {
return "Distance [feet=" + feet + ", inches=" + inches + "]";
}
}

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

Categories

Resources