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

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

Related

Java equals method not behaving as expected

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
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!(this.getName().equals(otherRestaurant.getName())))
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed))
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
return true;
}
public double getAverageTaxes() {
double total;
total = this.getPeopleServed() * this.getAveragePrice()
* super.CA_TAX_RATE;
return total;
}
}
package restaurantclient;
public class Store {
//Instance Variables
protected final double CA_TAX_RATE = 0.0884;
private String storename;
//Constructor
public Store(String storename) {
setName(storename);
}
//Getters (Accessors)
public String getName() {
return storename;
}
//Setters (Mutators)
public void setName(String storename) {
this.storename = storename;
}
//toString Method [Must Override]
#Override
public String toString() {
String directory = "Name of store: " + storename;
return directory;
}
//Equals Method
public boolean equals (Store storename) {
if (this == storename)
return true;
if (storename == null)
return false;
if (!(storename instanceof Store))
return false;
return true;
}
}
Above are the equals methods I'm calling. They are displaying the wrong answers: it should be in the first instance, "They are not equal" and in the second instance after setting everything equal to each other, it should display, "They are equal". I have tried very hard on this problem and many things have not worked. There are no overt errors it runs fine, but I am doing something wrong and some precise guidance would be a lot of help. Much of the vague hints have got me nowhere. I need something concrete, if this makes to you. Thanks again for the help. The following is the Client class:
package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonald's", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
System.out.println();
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal."); //SHOULD say "not equal" here EVERY TIME the second instance (next comment down) says "Equal"...this should never change.
System.out.println();
}
System.out.println();
r2.setName(r1.getName());
System.out.println(r1.toString());
System.out.println(r2.toString());
if (r1.equals(r2)) {
System.out.println("The objects are equal."); //Now that everything is equal, it should print "The Objects are Equal" but it doesn't. It's in lock-step with the previous instance. Changing some things like return true to return false might make both these instances "Are equal" and some might change them to "Not Equal" but they are never the way I want them, which is when 2 changes are made, they are not equal (first case) and when the third and final change is made (like this case here on this line) it should say "the obj are equal" but it doesn't.
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by the restaurant is: $");
System.out.println(r1.getAverageTaxes());
}
}
The reason that I see is simple, you are not getting the same name.
In equals, you are comparing super.getName() with otherRestaurant.getName()
If the superclass of Restaurant have a different format or return an other variable, since you compare it to Restaurant.getName(), this will compare different value. Using this.getName() to compare the same variable (or format of variable) is safer. Even if Restaurant.getName() is only returning the super.getName(), this would be safer if you changed the method of Restaurant (because you prefer it an other way).
Here is an example :
Restaurant:
public String getName(){
return "A restaurant " + name;
}
Super class :
public String getName(){
return name;
}
Will result into comparing "A restaurant : KFC" with "KFV".
Using the same getter assure you to return the same "format".
Aslo, your logic is wrong. You want to check if one of the value is different, if it is, return false. And if you reach the end of the method, meaning there where no difference leading to a return false, you return true.
if (this.getName() == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (!super.getName().equals(otherRestaurant.getName())) // added ! here
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != (otherRestaurant.peopleServed)) // change to != here
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
//No differences, then it is equals.
return true;
Note :
This condition could be shorten
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != (otherRestaurant.averagePrice)) // change to != here
return false;
Since it is doing the same thing (comparing the values) :
if (averagePrice != (otherRestaurant.averagePrice))
return false;
Edit :
You are having a problem of overriding.
In Store:
public boolean equals(Store s){}
And in Restaurant
public boolean equals(Object o){}
Since you are calling the method with a Restaurant (subclass of Store), the JVM will use the Store.equals method since it match the type, Restaurant.equals is not overriding it, it override the method in Object. Change to Store.equals(Object o) to correct this.
The method equals comes from Object so it should be always receiving an Object to prevent any problem like this one, if you specify the type in a method, it will not override correctly the method (depending on the type)
Seems you are checking for equality and then returning false, when you should check for not equality to return false.
else if (!super.getName().equals(otherRestaurant.getName()))
return false;
else if (peopleServed != (otherRestaurant.peopleServed))
return false;
else if (averagePrice != (otherRestaurant.averagePrice))
return false;
Also as asked, any reason to uses super.getName() ?
And since peopleServed & averagePrice cannot be null, the -1 check is not needed as the expected result we be the same as the equality check
And finally, I'm guessing the end return should be true, as it means it's different instance of an object, but they have all the same attributs.
Within your equals() method , If super.name() equals otherRestaurant.name() shouldn't you return true, here:
else if (super.getName().equals(otherRestaurant.getName())) return false;
Ok, that one will work in any cases:
#Override
public boolean equals (Object other) {
if (this == other)
return true;
if (other == null)
return false;
if (!(other instanceof Restaurant))
return false;
Restaurant otherRestaurant = (Restaurant) other;
if (name == null) {
if (otherRestaurant.getName() != null)
return false;
} else if (name!=otherRestaurant.getName())
return false;
if (peopleServed == -1) {
if (otherRestaurant.peopleServed != -1)
return false;
} else if (peopleServed != otherRestaurant.peopleServed)
return false;
if (averagePrice == -1) {
if (otherRestaurant.averagePrice != -1)
return false;
}
else if (averagePrice != otherRestaurant.averagePrice)
return false;
return true;
}
check it and reply if it is ok

Java calling method and trapping return

I'm having a problem calling a method and then trapping its return.
I need it to update the result so the next time round the loop it will see it and return a different message.
public class Patient {
private char patientStatus;
public boolean admit() {
if (patientStatus != 'S')
return false;
else
patientStatus = 'A';
return true;
}
This section is in the main() method
do {
Patient temp = null;
System.out.print("Enter selection: ");
menuSelect = sc.nextLine();
// validation
if (menuSelect.length() != 1) {
System.out.println("You must enter a single character");
} else {
menuAnswer = menuSelect.charAt(0);
switch (menuAnswer) {
case 'A':
case 'a':
// patient number
System.out.print("Enter patient number: ");
patNumber = sc.nextLine();
// search for patient number
for (int i = 0; i < pat.length && temp == null; i++) {
if (pat[i].getPatientNo().equals(patNumber)) {
temp = pat[i];
}
}
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean patStatus = temp.admit();
if (patStatus == false) {
System.out.println("Admitted");
} else if (patStatus == true) {
System.out.println("Already admitted");
}
}
}
}
} while (menuAnswer != 'x' && menuAnswer != 'X');
System.out.println("Exiting menu");
I don't know how to update the patStatus so the next time in the menu if you select 'A' and the same patient number it returns "Already admitted".
Let me know if there's enough code to understand what's happening.
Your Patient has the atribute for patientStatus but its value is never saved. Your admit() method needs to set the value for it.
Currently, your code only returns the value but does not save it.
Try this:
public class Patient {
private char patientStatus;
/** "Getter" method for patientStatus
*/
public char getPatientStatus(){
return patientStatus;
}
/** "Admits" the new patient, changing its patientStatus
* #return "true" if patient is admitted; "false" if patient was already admitted.
*/
public boolean admit() {
if (patientStatus != 'A')
patientStatus = 'A'; //set the value to Admitted
return true;
else
return false;
}
}
Then, in your loop, test the value for the admit() call:
if (temp == null) {
System.out.println("Patient not found");
} else {
System.out.println("Patient " + patNumber + " Found");
boolean admitted = temp.admit(); // try to admit the patient
if (admitted) {
System.out.println("Admitted");
} else { //You don't need another if here
System.out.println("Already admitted");
}
}
Since admitted is of type boolean, you don't need to use the == operator, as the if statement uses a boolean value as argument.
You don't need a second if statement after the else either, since boolean can only have two values, if it is not true, then it can only be false
/* You have to re-factor the code on these lines.
Maintain Patients class which holds admitted patients.*/
public class Patients{
private ConcurrentHashMap<Integer, Patient> allPatients = new ConcurrentHashMap();
private HashSet<Integer) admittedPatients = new HashSet();
public Patients(){
}
public void add(Patient p){
allPatients.put(p.getPatientId(),p);
}
public Patient removePatient(int patientId){
dischargePatients.remove(patientId);
return allPatients.remove(patientId);
}
public Patient getPatient(int patientId){
return allPatients.get(patientId);
}
public void admitPatient(int patientId){
admittedPatients.add(patientId);
}
public boolean dischargePatient(int patientId){
return admittedPatients.remove(patientId);
}
public boolean isAdmittedPatient(int patientId){
return admittedPatients.contains(patentId);
}
}
From `Patient.java` class, you can admit & discharge patient.
If getPatient() is null implies patient is not present in list.
Once he is present, isAdmittedPatient returns whether
he is admitted or not.

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 + "]";
}
}

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

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

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

Categories

Resources