I am trying to take a 3 class program and pass a boolean for reserving a room. I have driver program, building, room programs. I set the reserve to false and I can't figure out how to print out a text statement when it's already set to true. I think I am either doing the passing of the boolean through the classes from the driver wrong or missing something. I have played with reserveRoom in building class with an if statement to see if it's already true to print a statement and no matter which way I go it doesn't work.
Any help would be appreciated.
Thank you.
From my driver program that sends the boolean to the building program
System.out.print ("Which room would you like to reserve?");
System.out.print (building);
System.out.print ("reserve: ");
reservNum = input.nextInt();
building.reserveRoom(reserve, reservNum);
From my building class.
public void reserveRoom (boolean reserve, int count)
{
//class constant
//class variables
/*****************************************************/
room [count].updateReserve(reserve);
} // end
From the room class.
public void updateReserve(boolean newReserve)
{
//class constant
//class variables
/*****************************************************/
if (newReserve == false)
{
roomAvail = true;
}
else
{
roomAvail = false;
}
} // END
Well, there is some information missing in your question, however it think you are looking for:
public void updateReserve(boolean newReserve) {
if(newReserve && !roomAvail) {
System.out.println("Sorry this room is taken")
} else {
roomAvail = !newReserve;
}
}
With whatever i could understand about your question this is what i came up with -
public class Reservation {
public static void main(String args[]) {
Building building = new Building(20);
boolean reserve= false;
System.out.println("Which room would you like to reserve?");
System.out.println(building);
System.out.println("reserve: ");
int reservNum = 2;
building.reserveRoom(reserve, reservNum);
System.out.println("Is Reserved?:"+building.getRoom(reservNum).getRoomAvail());
}
}
class Building {
Room room[];
public Building(int numOfRooms) {
room = new Room[numOfRooms];
for(int i=0; i<numOfRooms; i++) {
room[i] = new Room();
}
}
public String toString() {
return "This Building has "+room.length+"rooms";
}
public Room getRoom(int roomNum){
return room[roomNum];
}
public void reserveRoom (boolean reserve, int count)
{
//class constant
//class variables
/*****************************************************/
room [count].updateReserve(reserve);
} // end
}
class Room {
boolean roomAvail;
public boolean getRoomAvail() {
return roomAvail;
}
public void updateReserve(boolean newReserve)
{
//class constant
//class variables
/*****************************************************/
if (newReserve == false)
{
roomAvail = true;
}
else
{
roomAvail = false;
}
} // END
}
Related
Hello friends I am trying to build a class Car for a project. There are many methods inside the following code as well as an if statement that I am having trouble building, consider the following code
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* #param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
What I want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`.
here I expected trips to be 1 but the result is the following:
Drive: false
trip: 0
I have tried this.isDriving==true; and basicaly wherever auto is inside the if statement I put this but the following error appears
non static variable cannot be referenced from static context
help me please!
What i want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenance is greater than 100 needsMaintenance should become true
Do this inside stop() method
fun stop() {
if (isDriving) {
tripsSinceMaintenance++;
}
if (tripsSinceMaintenance > 100) {
needsMaintenance = true;
}
isDriving = false;
}
You don't need to put == true inside of an if statement, it's doing that already,
if(someCondition) { // <-- this executes if the condition is true.
Also, you have conflicting conditions nested, meaning...
if (thisIsTrue) {
if (!thisIsTrue) {
// <--- unreachable statements
where you should be incrementing your variable is where you're setting "isDriving = true"
So your code would look like this:
public void drive() {
this.isDriving=true;
auto.tripsSinceMaintenance++;
}
I need to write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades.
Now this is my enumeration code:
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
B_MINUS(true),
C(true),
D(true),
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean isPassing() {
return this.passed;
}
#Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
What I am confused about is writing the main program. I think it could be quite straightforward but I have no clue on how to start it.
I don't want the whole code. Just a few lines to give me a head start. The rest I will try to figure out on my own.
I imagine you have a Student class that looks like this:
class Student {
protected Grade grade = null;
public Student(Grade g) {
this.grade = g;
}
}
Then you simply add a method in this class calling the isPassing method from your enum:
public boolean isPassing() {
if (this.grade != null)
return this.grade.isPassing();
return false;
}
This is supposing the passed boolean in Grade are correctly set and are invariant.
Hello i am writing a program that creates a method that can remove items from an arraylist and add them to another ArrayList (under certain conditions). This is the method I am supposed to create:
A method called giveAwayFish() which represents a person
returning his fish to the pond and/or giving them away to another fisher.
It will go through all of this person's fish ( the one giving the fish away) and see if the other fisher ( the one who will be receiving the fish) is willing to keep any. If the other fisher wants any, they are to be given to that fisher. If the fisher is unwilling to keep the fish, then these fish must be returned to the pond.
I tried writing out this method about a hundred times and I can not for the life of me figure out what to do. I was able to remove all the fish from the persons array but I do not know how to add them back. This is what I need help with.
Here is my code if it helps:
import java.util.*;
public class Fisher
{
private String name;
private Fish [] fishCaught;
private int numFishCaught;
private int keepSize;
public static int LIMIT = 10;
public String getName()
{
return this.name;
}
public int getNumFishCaught()
{
return this.numFishCaught;
}
public int getKeepSize()
{
return this.keepSize;
}
public Fisher(String n, int k)
{
name = n;
keepSize = k;
}
public String toString()
{
return(this.name + " with " + this.numFishCaught + " fish as follows:");
}
private ArrayList<Fish> fishesCaught = new ArrayList<Fish>();
public void keep(Fish fish)
{
if(this.numFishCaught < LIMIT)
{
fishesCaught.add(fish);
numFishCaught++;
}
}
public boolean likes(Fish fish)
{
if(fish.size >= this.keepSize && fish.species != "Sunfish")
{
return true;
}
else
{
return false;
}
}
public void listFish()
{
System.out.println(this.toString());
for(Fish fish : fishesCaught)
{
System.out.println(fish.toString());
}
}
public void goFishingIn(Pond pond)
{
Fish fish = pond.catchAFish();
if(likes(fish))
{
this.keep(fish);
}
else
{
pond.add(fish);
}
}
public void giveAwayFish(Fisher fisher, Pond pond)
{
Fish fish = fishesCaught;
if(fisher.likes(fish))
{
fishesCaught.clear();
this.numFishCaught = 0;
}
}
}
Biggest problem here is (yes, there are lots of other problems), in your giveAwayFish(), you wrote
Fish fish = fishesCaught;
However fishesCaught is a List<Fish>. That can't even compile.
I believe what you want to do is something like (in psuedo code):
for (Fish fish : fishesCaught) {
if (fisher.like(fish)) {
fisher.keep(fish);
} else {
pond.addFish(fish);
}
}
fishesCaught.clear();
I have 3 Classes (Printer, PaperTray and Machine) and my Main Java class (HelloWorld).
I am expecting to see "Load more paper!" as the output when this "myPrinter.print(2)" is called yet the output shows "My Printer is On!" twice, as though there is paper in the tray. I should only see the output showing the printer as on twice if there is enough paper being passed into loadPaper(which has been commented out for the time being until I get the load paper working):
import printing.Printer;
public class HelloWorld {
public static void main(String[] args)
{
Printer myPrinter = new Printer(true, "MY PRINTER");
//myPrinter.loadPaper(3);
myPrinter.print(2);
}
}
From my Printer class:
package printing;
public class Printer extends Machine
{
private String modelNumber;
private PaperTray paperTray = new PaperTray(); //printer now HAS paper tray
public Printer(boolean isOn, String modelNumber)
{
super(isOn); //calls the constructor of the machine class - Super calls inherited parent
this.modelNumber = modelNumber;
}
public void print(int copies)
{
String onStatus = "";
if(isOn)
{
onStatus = " is On!";
}
else
{
onStatus = " is Off!";
}
String textToPrint = modelNumber + onStatus;
while(copies > 0 && !paperTray.isEmpty())
{
System.out.println(textToPrint);
copies--;
paperTray.usePage();
}
if(paperTray.isEmpty())
{
System.out.println("Load more paper!");
}
}
//for each
public void printColours()
{
String[] colours = new String[] {"Red", "Blue", "Green", "Yellow" };
//for current colour "in" colours
for(String currentColour : colours)
{
if("Green".equals(currentColour))
{
continue;
}
System.out.println(currentColour);
}
}
public void print(String text)
{
System.out.println(text);
}
public String getModelNumber()
{
return modelNumber;
}
public void loadPaper(int count)
{
paperTray.addPaper(count);
}
}
When ".isEmpty()" is called, the value of pages is -2 yet I believe ".isEmpty()" only works when the value is equal to 0 exactly? So this is where I am guessing my problem is. Yet the code I have is (99% certain) the same as the tutors example.
The PaperTray class is :
public class PaperTray {
int pages = 0;
public void addPaper(int count)
{
pages += count;
}
public void usePage()
{
pages--;
}
public boolean isEmpty()
{
return pages > 0;
}
}
Machine class:
public class Machine {
protected boolean isOn;
public Machine(boolean isOn)
{
this.isOn = isOn;
}
public void TurnOn()
{
isOn = true;
}
public void TurnOff()
{
isOn = false;
}
}
Any help is appreciated.
Your isEmpty() method is wrong in PaperTray, it now returns true if pages > 0 (when it is full), and returns false if pages <= 0 (when it is empty).
You need to switch the condition to pages == 0 or to be absolutely sure pages <= 0.
Your isEmpty() definition seems to be wrong
public boolean isEmpty()
{
return pages > 0; //shouldn't it be pages <=0 ?
}
So the exact wording is,
"Write a private method isValid(aRating) that returns true if the given rating is valid, which is between 1-10."
private void isValid(aRating)
{
}
What Goes in the Method above in order to return a true value if given rating is valid, Validity meaning a number 1-10.
This is what i attempted, the instructor wants it the "proper way" This is just an example of what i attempted at, It is a different program completely.(Ignore if confusing).
private void isValid(int hour, int minute)
{
if (hour >= 0 && hour <=23)
{
System.out.println("Hour is valid");
hourIsValid = true;
}
else
{
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
Would this be correct
private boolean isValid(int aRating)
{
if (aRating >= 1 && aRating <= 10)
return true;
else
return false;
}
The problem demands a function that returns true under some conditions, so the signature cannot be
private void isValid(int aRating) {}
it needs a return type. Now, true's type is boolean, so make it
private boolean isValid(int aRating) {
return /* validity test here */;
}
Calling Private Methods
Calling a private method from a public one is exactly the same as calling any other method:
public void doStuff() {
System.out.println("Stuff done.");
}
private void doOtherStuff() {
System.out.println("Other stuff done.");
}
public void showHowItWorks() {
doStuff();
doOtherStuff();
// or if you prefer this style:
this.doStuff();
this.doOtherStuff();
}
The important difference is that you can only call private methods from inside the class where they were defined:
class PublicExample {
public static void doStuff() {
System.out.println("Stuff done.");
}
}
class PrivateExample {
private static void doStuff() {
System.out.println("Stuff done.");
}
}
class Example {
public static void Main(String[] args) {
PublicExample.doStuff(); // Works
PrivateExample.doStuff(); // Doesn't work (because it's private and defined in a different class)
}
}
Return Values
private void isValid(int hour, int minute) {
if (hour >= 0 && hour <=23) {
System.out.println("Hour is valid");
hourIsValid = true;
} else {
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
The problem with this approach is that your program immediately dies if you input a bad hour or minute. What if I want to loop until I get a good input?
I think the main problem is that you don't know how to return a value from a method. Here's an example of a function that always returns true:
public static boolean trueExample() {
return true;
}
public static void main(String[] args) {
boolean returnValue = trueExample();
System.out.println("trueExample() returned " + returnValue);
}
You can also make it more complicated:
/**
* #return the input value minus one.
*/
public static int oneLess(int num) {
return num - 1;
}
public static void main(String[] args) {
int num = 10;
// Print 10
System.out.println(num);
// Print 9
num = oneLess(num);
System.out.println(num);
// Print 8
num = oneLess(num);
System.out.println(num);
}
Here's one that will return true if num is in the range 10-20 and false otherwise:
public boolean isValid(int num) {
return num >= 10 && num <= 20;
}
This version does exactly the same thing, but you may find it easier to read since it's more explicit:
public boolean isValid(int num) {
/* Numbers less than 10 are invalid */
if(num < 10) {
return false;
}
/* Numbers greater than 20 are invalid */
else if (num > 20) {
return false;
}
/* By process of elimination, everything else is valid */
else {
return true;
}
}
Let me know if that's not enough to help you with your problem.
Just like you would call any normal method as long as the private method is visible to the public method.