So which floor the lift is on should be able to be read and changed, but only within the allowed range for just that house the lift is installed in. I'm trying to get an "If" condition working looking for a boolean true value from method "validFloor".
Based on my very beginner knowledge of Java, I assume putting an "If" condition in the set-method is a proper attempt?
private int currentFloor = 0;
private int numberOfFloors;
private boolean validFloor = false;
public Elevator(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
//Sets the allowed number of floors (0 to 100)
public void allowedNumberOfFloors() {
if (numberOfFloors < 2) {
numberOfFloors = 2;
} else if (numberOfFloors > 100) {
numberOfFloors = 100;
}
}
//Checks validity of the elevator floor in relation to total floors.
public void validFloor() {
if (currentFloor > numberOfFloors && currentFloor < 0) {
this.validFloor = false;
}
}
//Checks whether the specified floor is in reasonable range.
public void setFloor(int currentFloor) {
if (validFloor) {
this.currentFloor = currentFloor;
}
}
public int getFloor() {
return currentFloor;
}
public String toString() {
return "Number of floors: " + numberOfFloors + "\nCurrent floor: " + currentFloor;
}
For example, if you try to move the lift to floor 74 in a house that only has 5 floors, it should not work. I want the hiss to start at bottom floor 0, hence the 0 value in class variable "currentFloor".
The If condition in the "validFloor" method doesn't seem to be recognized at all. Instead all that matters is the boolean value I put on the class variable validFloor.
You never call the validFloor() method, so the value of validFloor is never changed. Also, you code never sets validFloor to true anywhere, so it wouldn't even matter if you called validFloor(), because it can only set validFloor to false, or leave it at the initial value of false.
The "correct" way to do something like this is:
public boolean isValidFloor(floor) {
// It seems weird to me that 0 is a valid floor. Is that correct?
// If floors are zero-indexed, the top floor should actually be numberOfFloors-1.
return floor >= 0 && floor <= this.numberOfFloors;
}
public void setFloor(int newFloor) {
if (isValidFloor(newFloor)) {
this.currentFloor = newFloor;
}
}
Notice that there's no need to even keep around a validFloor variable. We can just check whether or not a floor is valid every time we need to without saving the result.
Related
The assignment is asking me to create a class named Vehicle that stimulates a car moving along a 40 block stretch of road.
Here's more information:
Your class will build a vehicle and keep track of its location on the road. Location values may range from -20 to 20. A location value of 0 represents block 0, a location value of 1 represents block 1, a location value of 2 represents block 2, etc. If the user tries to move the vehicle beyond block +20 or -20, set the location to +/- 20 respectively.(I dont understand how to do this part)
Variable
int location - An integer that holds the current block location of the car on the road, with possible values ranging from -20 to 20.
Methods
Vehicle () - Sets location to 0.
Vehicle (int loc) - If loc is between -20 and 20 inclusive, sets location to loc. Otherwise, sets location to 0.
void forward () - Increments the vehicle forward one block. Do not let the user move past block 20.
void backward () - Increments the vehicle backward one block. Do not let the user move past block -20.
int getLocation () - Returns an integer representing the block location of the car.
String toString () - Returns a String representation showing the vehicle as an # character, with spaces to show its location. When the vehicle is at location -20 the # character appears at the start of the String. When the vehicle is at a higher position, one space for each number from -20 to the car's current location appears before the #. For example if the car is at block -10, the method will return " #" (10 spaces then the '#'). If the car is at block 5 the method will return " #" (25 spaces then the '#').
Here's my code so far(this is in my Vehicle.java file) :
public class Vehicle
{
private int location;
public Vehicle(int loc)
{
return location;
}
public void forward()
{
if (location>=-20 && location <=20)
{
location++;
}
}
public void backward()
{
if (location>=-20 && location <=20)
{
location--;
}
}
public int getLocation()
{
return location;
}
public String toString()
{
return "";
}
}
Here is the runner file:
import java.util.Scanner;
public class runner_Vehicle
{
public static void main (String str[]){
Scanner scan = new Scanner(System.in);
Vehicle v = new Vehicle ();
String instruction = "";
while(!instruction.equals("q")){
System.out.println(v);
System.out.println("Location: " + v.getLocation());
System.out.println("Type \"f\" to move forwards, \"b\" to move backwards, \"n\" for new vehicle, \"q\" to quit.");
instruction = scan.nextLine();
if(instruction.equals("f")){
v.forward();
}
else if(instruction.equals("b")){
v.backward();
}
else if(instruction.equals("n")){
System.out.println("Starting location for new vehicle?");
int start = scan.nextInt();
v = new Vehicle(start);
scan.nextLine();
}
else if(!instruction.equals("q")){
System.out.println("Instruction not recognized.");
}
}
}
}
If the user tries to move the vehicle beyond block +20 or -20, set the location to +/- 20 respectively. (I dont understand how to do this part)
Simply check it and cap the value
public void forward()
{
location++;
if (location > 20) location = 20;
}
public void backward()
{
location--;
if (location < 20) location = -20;
}
Regarding the toString method - Look at the StringBuilder class
StringBuilder sb = new StringBuilder();
for (int i = -20; i <= 20; i++) {
if (i == getLocation()) {
sb.append("#");
}
else sb.append(" ");
}
return sb.toString();
First time answering a question, but hope I can be of some help:
I've tried to explain what each thing does in places I thought you might have been confused. If you are going to hand this in, please remove the comments.
class Vehicle {
private int location;
public Vehicle() {
// Known as the constructor.
// Creates an instance of the class, meaning it creates the vehicle object when you say
// Vehicle car = new Vehicle();
location = 0;
}
public Vehicle(int loc) {
// known as a parameterized constructor, which is just a constructor but you give it some default values.
// It does not return a value, all it does it make the object in question.
// In this case, it would be a Vehicle object.
if (loc >= -20 && loc <= 20) {
location = loc;
}
}
public void forward() {
location++;
if (location >= 21) {
location = -20;
}
}
public void backward() {
location--;
if (location <= -21) {
location = 20;
}
}
public int getLocation() {
return location;
}
public String toString() {
String output = "";
for (int i = -20; i < location; i++) {
output += ' ';
}
return output + '#';
}
}
Hopefully that helps!
I'm trying to create a boolean method called hasBiggerTank that if the size is bigger or equal to 4 it has enough fuel else not enough fuel.
I am trying to call results of a boolean method in a main method but the result I got is both car1 and car2 printing out the word true when it should output
Expected output:
"goodfuel consumptions" plus car2 should be false.
I'm new to Java, I need some help.
// method
public boolean hasBiggerTank(int size) {
if (size <= 4) {
return true;
} else {
return false;
}
}
public class Start {
public static void main(String[] args) {
boolean hasBiggerTank = true;
int size = 0;
if (size <= 4) {
System.out.println("Good fuel consumptions");
} else {
System.out.println("Not enough fuel");
}
Car car1 = new Car();
car1.hasBiggerTank(6);
System.out.println("Car 1 efficiency: " + car1.hasBiggerTank(size));
Car car2 = new Car();
car2.hasBiggerTank(2);
System.out.println("Car 2 efficiency: " + car2.hasBiggerTank(size));
}
}
public static boolean hasBiggerTank(int size) { \\method
if (size <= 4) {
return false;
}
return true;
}
public class Start {
public static void main(String[] args) {
int size = java.util.Scanner.nextInt();
boolean hasBiggerTank = hasBiggerTank(size);
if(hasBiggerTank) {
System.out.println("Good Big Fuel Tank");
}
else {
System.out.println("Not big enough fuel Tank");
}
}
}
This is how to call a boolean returning method from main method.
OK, so I think that the real reason you are getting the wrong answer is that the logic of your hasBiggerTank method is incorrect.
Based on the name of the method, and the way you are using it, I think it is supposed to return true if and only if the car's tank size is bigger than the size argument.
But if you look at the code, that is NOT what you have implemented. Instead, your method is ignoring the car's tank size, and is just testing if (in effect) the user has entered a number less or equal to 4.
Solution: think about hasBiggerTank should really be doing ... and implement that.
But there is also something odd about this whole thing. In the real world a car's gas tank size and its fuel efficiency are not the same thing. But perhaps this is just an artifact of an unrealistic set of requirements for a homework exercise ...
as you said in question:
that if the size is bigger or equal to 4 it has enough fuel else not enough fuel.
if the size is greater or equal to 4 then the method hasBiggerTank have to return true and the problem is with your condition inside hasBiggerTank method and you need to change it to this:
public static boolean hasBiggerTank(int size) {
if (size >= 4) {
return true;
} else {
return false;
}
}
the next problem is in your main() method, again you are putting the conditions in wrong format which it should be changed to this:
int size = 0;
if (size >= 4) {
System.out.println("Good fuel consumptions");
} else {
System.out.println("Not enough fuel");
}
in here according to your question we are checking whether the size is greater or equal to 4 or not if its true then Good fuel consumptions will be printed.
I've been given an assignment to edit a game and add different elements to it, one was the ability to restore player life when interacting with an object which I have completed.
The next step is to stop this from working when the players life is max (100).
My idea then was to create a method with a condition (and if it is true, stop my life adding method from working / being called.)
Example:
private void checkMaxLife() {
if (playerLife==100) {
//Stop method addLife from working
}
}
Would this be possible and what is the syntax?
EDIT:
This was the fix, added playerLife < 100 to the collision method instead.
private void foodAddLife() {
//Check food collisions
for (int i = 0; i < food.length; ++i) {
if (playerLife < 100 && food[i].getX() == player.getX() && food[i].getY() == player.getY()) {
//We have a collision
++playerLife;
}
}
It seems you don't need checkMaxLife, just use the attribute playerLife in the method addLife
private void addLife() {
if (playerLife < 100) {
playerLife++; // or whatever value
}
}
With 2 methods, you see that one is useless
private boolean isFullLife() {
return playerLife >= 100;
}
private void addLife() {
if (!isFullLife()) {
playerLife++; // or whatever value
}
}
You just return the function when player life is MAX_VALUE.
private void addLife() {
if(playerLife>=100)
return;
// Do Whatever you need to do
}
I'm pretty new to java, but I'm trying to make a simulation of the finger game, 'Sticks', using my limited knowledge. This may not be the neatest, but if you're going to make a suggestion on me to do something, link a page explaining what that thing is, and I'll read it.
Ok, so the issue comes up basically when I call a method to decide who's turn it is and trying to return the value for the "count" up to 5, but it's not returning to main()
public static int TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return Death;
}
Death is there because I was getting an error telling me that I always need to return SOMETHING so I'm returning a static value.
Basically, the problem is getting PLH (player left hand) or PRH (player right hand) to return to main. If I'm not wrong, they should return as their initial variable name (PL, and PR) with the returned value correct? If not, what can I do to fix this?
The code is a lot larger than this, and this issue is happening throughout the whole program, so I'm showing just 1 method and assuming they're all the same issue; the methods are almost all the same.
Also, while I'm typing a question already, is nextInt() the best way to do a random number generator? When I had it as nextInt(1) it was exclusively attacking the left hand, and when I switched it to nextInt(2) now it's attacking both, but occasionally the code... "crashes" (what I mean by crashes is that it generates a number outside of what the If statements are looking for). I obviously need to to generate either a 1 or a 2 (or 0 and 1 if 0 counts).
You can change your code to
public static Integer TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return null;
}
NOTE: make sure you first check for null values where you call this function.
You are generating random number twice, this is why you can observe "strange" behvior.
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5) {
...
}
else if(botAtk.nextInt(2) == 0 && PLH <= 5) {
...
}
Try generating random only once:
Random botAtk = new Random();
boolean right = botAtk.nextInt(2) == 1; // flip coin only once
if(right && PRH <= 5) {
...
}
else if(!right && PLH <= 5) {
...
}
I know the answer will not get accepted, because there is an accepted one, but nevertheless:
I suspect that you have a wrong understanding of method parameter passing in Java.
What I read from your question and comments is that you expect this to work:
public static int psInt = 0;
static void main() {
int someNumber = 1;
int someOtherNumber = 5;
method1( someNumber, someOtherNumber );
// You expect "someNumber" to be 6 right now.
// But in fact, the value will be unchanged.
// What WILL work: psInt is 0 now
method3(); // this method will modify the static class var
// psInt is 5 now.
}
static void method1( int numParam, int someothervalue ){
numParam = numParam + someothervalue;
}
static void method2( int someNumber, int someothervalue ){
someNumber = someNumber + someothervalue; // <- same name won't work either!
}
public static void method3(){
psInt = 5;
}
But in Java method arguments are passed by value. That is: a copy!
So no matter how you name the variables and arguments, you will never have an "out" argument here.
What you can do:
In a static method, you can use and modify static class variables.
In a non-static method, you can use and modify non-static and static class variables.
You can pass a State-Object, of which you can modify field values.
You can return a value.
... there are more possibilites. These just to start with.
In your case, 4. does not make so much sense, because you wouldn't know if it is the new right or left hand value.
Trying to add objects to a ArrayDeque at random intervals. This is what I have
for (int i = 0; i <= 100; i ++) {
if (window.isEmpty()) {
Customer customer = new Customer(r.nextInt(10)+1);
q.add(customer);
window.beginService();
}
else {
Customer customer = new Customer(r.nextInt(10)+1);
q.add(customer);
window.beginService();
totalCustomers++;
totalServiceTime += window.serviceTime;
totalWaitTime += customer.getArrivalTime();
}
}
The other methods being used are
public boolean isEmpty() {
if (serviceTime == 0) {
return true;
}
else
return false;
}
public void beginService() {
if (isEmpty()) {
serviceTime = r.nextInt(10)+1;
}
else
serviceTime += r.nextInt(10)+1;
}
public Customer(int arrivalTime) {
this.arrivalTime = arrivalTime;
}
public int getArrivalTime() {
return arrivalTime;
}
When I print out my customer count it is equal to my clock time, which should not be as customers are added at random intervals of 1-10. Any ideas?
Are you defining your "clock time" as the value of i? If so, I'm not sure why you would expect it and totalCustomers to be different.
In your for loop, you add a customer regardless of whether or not the windows is empty. After the first time around, the window will never be empty because you are always beginning service which always increments the serviceTime by at least 1.
So after the first iteration of the loop, the else branch of your if will exclusively be executed and totalCustomers will always increment alongside of i.
I think you have bigger logic gaps in your code but you haven't been very clear with how you've framed your question or shown your code. It is unclear how serviceTime is declared or what the code is supposed to be doing. You never seem to take an item off of the queue. If you need more help than this you need to put some more effort into your question.