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++;
}
Related
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
}
I'm learning object-oriented programming and started learning about inheritance. The assignment my teacher gave me was to make a counter object with 6 "buttons": Increment, Decrement, Reset, AddMemory, ResetMemory, and Quit. It is fairly straight-forward what each button does.
The requirements are that I have to use the JOptionPane command, I have to make a Counter class with a counter attribute, increment, decrement, reset, and quit methods, I have to make a MemoryCounter class with a memory attribute, restMemory, and addMemory method. I also have to make a MemoryCounterConsoleMenu class which makes the input box from the JOptionPane command and executes the appropriate method. The final thing I have to do is make a MemoryCounterTest class that brings the MemoryCounterConsoleMenu and MemoryCounter classes together
So I did all that and here it is:
The first one is the Counter class
public class Counter
{
private int counter = 0;
public void increment()
{
setCounter(getCounter() + 1);
}
public void decrement()
{
setCounter(getCounter() - 1);
}
public void reset()
{
setCounter(0);
}
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
This is the MemoryCounter class
public class MemoryCounter extends Counter
{
private int memory = 0;
public void resetMem()
{
setMemory(0);
}
public void addMem()
{
setMemory(getCounter());
}
public void setMemory(int memory)
{
this.memory = memory;
}
public int getMemory()
{
return memory;
}
}
Next is the MemoryConsoleMenu
public class MemoryCounterConsoleMenu
{
static MemoryCounter memCounter = new MemoryCounter();
static Counter counter = new Counter();
public static int console()
{
System.out.println(memCounter.getMemory());
Object[] options = {"Reset Mem", "Add Mem", "Increment", "Decrement", "Reset", "Quit" };
int objectIndex = JOptionPane.showOptionDialog(null, "Counter = " + counter.getCounter() + "Memory = "
+ memCounter.getMemory(), "MemoryCounter",JOptionPane.PLAIN_MESSAGE,
JOptionPane.PLAIN_MESSAGE, null, options, options[5]);
return objectIndex;
}
public static int change(int objectIndex)
{
if(objectIndex == 0)
{
memCounter.resetMem();
return 1;
}
else if(objectIndex == 1)
{
memCounter.addMem();
return 2;
}
else if(objectIndex == 2)
{
counter.increment();
return 3;
}
else if(objectIndex == 3)
{
counter.decrement();
return 4;
}
else if(objectIndex == 4)
{
counter.reset();
return 5;
}
else
{
return 6;
}
}
}
Finally, there is the MemoryCounterTest
public class MemoryCounterTest
{
public static void main(String[] args)
{
MemoryCounterConsoleMenu memoryConsole = new MemoryCounterConsoleMenu();
for(int i = 0; i != 6;)
{
i = memoryConsole.change(memoryConsole.console());
}
}
}
Everything works properly except for the memory value. It stays at a constant zero. I've done some troubleshooting myself and found that the only problem in the code is in the "addMem()" method is the MemoryCounter class particularly the implementation of the "getCounter()" method. It will only return 0 for some reason.
After figuring this out I have made no ground on why the problem is occuring or how to fix it
It stays at 0 because they are two separate counters.
MemoryCounter class extends the Counter class, so you don't need a separate
static Counter counter = new Counter();
Just do everything via memCounter.
I am currently making a plugin from the 1.8 Bukkit API. This question however, has to do with booleans. From the beginning of my class file, I have this declaration of a boolean
public static boolean lockchat = false;
Then I have another boolean in the class file that is used for Bukkit commands:
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args)
This boolean returns true at the end, which I think is making the lockchat boolean return true also. If I return false, I am pretty sure that the command code will not return to the user.
My problem is that in this part of my code:
if(lockchat == true)
{
s.sendMessage("unlocked.")
lockchat = false;
}
else
{
s.sendMessage("locked.");
lockchat = true;
}
The declaration at the beginning does not seem to matter here, because this always sends me the message unlocked.
I have tried to put the declaration inside of the second boolean, but it throws me errors and warnings.
Since the second boolean is returning true, I think that the lockchat boolean is returning too. If I would change it to return false, lockchat would probably return false also, resulting in another problem.
I want to find a way to have the boolean declaration stay false, while having it changed to true/false inside of the second boolean, as shown. How would I do this?
NOTE: This variable is not used anywhere else in my code.
EDIT: I don't think this will make a difference, but I am testing for the label string to be "lockchat", the same as the boolean name. This probably wouldn't change anything, but just giving more information.
FULL CLASS FILE CODE:
package dev.td6.duocraft.commands;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import dev.td6.duocraft.main.Duocraft;
public class DCCommandLockChat implements CommandExecutor, Listener
{
Duocraft plugin;
public DCCommandLockChat(Duocraft instance)
{
plugin = instance;
}
public String colorize(String msg)
{
String coloredMsg = "";
for(int i = 0; i < msg.length(); i++)
{
if(msg.charAt(i) == '&')
coloredMsg += 'ยง';
else
coloredMsg += msg.charAt(i);
}
return coloredMsg;
}
public static boolean lockchat = false;
#SuppressWarnings("deprecation")
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args)
{
if(s instanceof Player)
{
Player p = (Player) s;
if(label.equalsIgnoreCase("lockchat"))
{
if(p.hasPermission("duocraft.lockchat"))
{
if(args.length >= 1)
{
if(args.length >= 2)
{
s.sendMessage("Too many arguments. </lockchat [time]>");
}
else
{
if(lockchat == true)
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
else
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked.");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
}
}
else
{
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
}
}
else
{
p.sendMessage("no access");
}
}
}
else
{
if(label.equalsIgnoreCase("lockchat"))
{
if(args.length >= 1)
{
if(args.length >= 2)
{
s.sendMessage("Too many args. </lockchat [time]>");
}
else
{
if(lockchat == true)
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked.");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked.");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
else
{
int time = Integer.valueOf(args[0]);
s.sendMessage("locked");
lockchat = true;
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable()
{
#Override
public void run()
{
Bukkit.broadcastMessage("unlocked");
lockchat = false;
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}
, time*20, time*20);
}
}
}
else
{
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
}
}
}
return true;
}
#EventHandler
public void chatLocked(AsyncPlayerChatEvent e)
{
if(lockchat==false)return;
Player p = e.getPlayer();
if(p.hasPermission("duocraft.lockchat.bypass"))return;
p.sendMessage("chat is locked.");
e.setCancelled(true);
}
}
EDIT: Also public static boolean lockchat = false; Is not being modified in any way by any other class files.
EDIT: I am using Java 7 for this.
Just so you know, in your full source you use the following code:
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
more specifically, you are sending "unlocked" no matter which path the code follows.
Edit: I reformatted your code to reduce some of the duplication. This version fails fast if the CommandSender is a player without permission or the label is not "lockchat". I inferred that the intention is that executing "/lockchat" without an argument should toggle locking immediately, while executing it with an argument should make it toggle for the specified number of seconds and then toggle back. The code below should do this (at least as far as ensuring lockchat always has the intended value, but I haven't tested it.
Also, I don't know if the Runnable will be called on a different thread, but if it is you should synchronize all accesses to the shared lockchat variable. At the very least, making it volatile (as I do below) may prevent some confusion amongst the threads as to its actual value.
public static volatile boolean lockchat = false;
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
// If this is not the 'lockchat' command, then fail fast
if (!label.equalsIgnoreCase("lockchat")) return true;
// If s is a Player then check the player has permission and fail fast
// if not.
if (s instanceof Player) {
Player p = (Player) s;
if (!p.hasPermission("duocraft.lockchat")) {
p.sendMessage("no access");
return true;
}
}
switch (args.length) {
case 0:
lockchat = !lockchat;
s.sendMessage(lockchatStatus());
break;
case 1:
int ticks = Integer.valueOf(args[0]) * 20;
final boolean originalLockChat = lockchat;
lockchat = !originalLockChat;
s.sendMessage(lockchatStatus());
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
#Override
public void run() {
lockchat = originalLockChat;
Bukkit.broadcastMessage(lockchatStatus() + ".");
plugin.getServer().getScheduler().cancelTasks(plugin);
}
}, ticks, ticks);
break;
default:
s.sendMessage("Too many arguments. </lockchat [time]>");
break;
}
return true;
}
private String lockchatStatus() {
return lockchat ? "locked" : "unlocked";
}
As stated in Julian's answer, your code is returning unlocked no matter what the value :
if(lockchat == true)
{
s.sendMessage("unlocked");
lockchat = false;
}
else
{
s.sendMessage("unlocked");
lockchat = true;
}
As per your comment regarding as to why it is not blocking the chat, are you sure you registered your listener? To register your listener, put this line in your onEnable() method in your Main class :
getServer().getPluginManager().registerEvents(new DCCommandLockChat(), this);
Where DCCommandLockChat() is your Listener class and 'this' is your class that extends JavaPlugin.
What this basically does is register your listener for your plugin because otherwise, the server wouldn't pass any events to your listener and so your listener wouldn't know what would be happening on the server.
Also, as for the method itself returning true or false, both values will still run the command. As far as I know, the only time the return value of the onCommand method matters is when you're using aliases in your plugin.yml. If the method returns false, then the server will send the player a message with the aliases. Aside from that, it doesn't really matter.
You should give the boolean (lockchat) the value you want in the constructor of your class.
To answer your question:
I want to find a way to have the boolean declaration stay false, while having it changed to true/false inside of the second boolean, as shown. How would I do this?
At the beginning of the body of whichever statement you want, make a temporary variable to store lockChat's value.
boolean lockChatTemp = lockChat;
Then, use and modify that value within your function. This way, lockChat will keep its value throughout.
Also,
if (lockChat == true)
can be replaced with
if (lockChat) since the statement inside the parentheses evaluates to a boolean, and lockChat is already a boolean.
I'm wrote a method to simulate a coin toss, however, I do not know how to call this method in the main. Tips would really be appreciated!
(Here is the method, I didn't post the entire code because there are 8 other methods in this code).
public static boolean headsOrTails()
{
boolean coinState;
if (Math.random() < 0.5) {//heads 50% of the time
coinState = true; //heads
}
else {
coinState = false; //tails
}
return coinState;
}
You should call like :
public class Abc {
public static void main(String[] args) {
System.out.println(headsOrTails());
}
public static boolean headsOrTails() {
boolean coinState;
if (Math.random() < 0.5) {//heads 50% of the time
coinState = true; //heads
} else {
coinState = false; //tails
}
return coinState;
}
}
and it will print the output of the function as true or false.
Try this:
boolean isHead = headsOrTails();
if(isHead){
System.out.println("Heads");
}else{
System.out.println("Tails");
}
if value of isHead is true you have a Head :)
You can also improve readability of your code by shortening the boolean evaluation (like Boann mentioned):
public class CoinToss {
public static void main(String[] args) {
headsOrTails();
}
public static boolean headsOrTails() {
return Math.random() < 0.5;
}
}
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.