This is is the code:
public class monkeyTrouble {
public static void main(String[]args){
monkeyTrouble s = new monkeyTrouble();
s.trouble(false, false);
}
public boolean trouble (boolean aSmile, boolean bSmile) {
if (aSmile == true && bSmile == true){
return true;
} else if (aSmile == false && bSmile == false) {
return true;
} else {
return false;
}
}
}
How can I run the boolean method in the main method so it will correctly run?
First, you are already running your method; you aren't displaying or storing the result. You could print the result like
public static void main(String[]args){
monkeyTrouble s = new monkeyTrouble();
System.out.println(s.trouble(false, false));
}
Also, your method could be simplified like
public boolean trouble (boolean aSmile, boolean bSmile) {
return aSmile == bSmile;
}
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 have two functions which check if all elements of an array or list are true. I'm having trouble combining the two. How can I make the functions into one generic Java function.
public static boolean allTrue(boolean[] booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
public static boolean allTrue(List<Boolean> booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
If you're using Guava, you can wrap the boolean array in Booleans.asList() and pass it as a list:
public static boolean allTrue(boolean[] booleans) {
return booleans != null && allTrue(Booleans.asList(booleans));
}
As per https://stackoverflow.com/a/5606435/2310289
You could just accept an Object
public static boolean allTrue(Object booleans) {
and then check for instanceof boolean[] or instanceof List<Boolean> and then perform different code within the method.
Again, not really an improvement, but a bit closer to code unification
I think the answer given by #Joel was a good one, except for the issue pointed out in the comment. If we just convert boolean[] to Boolean[], we can try the following:
public static boolean allTrue(List<Boolean> booleans) {
if (booleans == null) {
return false;
}
for (boolean bool : booleans) {
if (!bool) {
return false;
}
}
return true;
}
public static boolean allTrue(boolean[] booleans) {
Boolean[] newArray = new Boolean[booleans.length];
int i = 0;
for (boolean value : booleans) {
newArray[i++] = Boolean.valueOf(value);
}
return Arrays.asList(newArray);
}
The common ancestor for List<Boolean> and boolean[] is Object, so unless you are okay with allTrue(Object booleans), you cannot do it with one method.
If you change your method signature to allTrue(Iterable<Boolean> booleans), all you have to do is create a special Iterator<Boolean> to traverse the boolean array.
import java.util.Iterator;
import java.util.NoSuchElementException;
public class BooleanAllTrue {
public static boolean allTrue(Iterable<Boolean> booleans) {
if (booleans == null) return false;
for (Boolean bool : booleans) {
if (!bool) return false;
}
return true;
}
public static Iterable<Boolean> asIterable(final boolean[] booleens) {
return new Iterable<Boolean>() {
public Iterator<Boolean> iterator() {
final boolean[] booleans = booleens;
return new Iterator<Boolean>() {
private int i = 0;
public boolean hasNext() {
return i < booleans.length;
}
public Boolean next() {
if (!hasNext()) throw new NoSuchElementException();
return booleans[i++];
}
public void remove() {throw new UnsupportedOperationException("remove");}
};
}
};
}
public static void main(String [] args) {
System.out.println(allTrue(asIterable(new boolean[]{true, true})));
System.out.println(allTrue(asIterable(new boolean[]{true, false})));
try {
asIterable(new boolean[0]).iterator().next();
} catch (NoSuchElementException e) {
// expected
}
}
}
And finally the allTrue(boolean[] booleans) method.
public static boolean allTrue(boolean[] booleans) {
return allTrue(asIterable(booleans));
}
I want specific object with all it's values by using it's unique id of object from object list.
I have tried but i am getting index -1 while running below code.
List<JobDataDetail> jobList = getJobList();
JobDataDetail object = jobList.get(jobList.indexOf(new JobDataDetail(jobReferenceId)));
from the class
public class JobDataDetail implements Serializable,Comparable<JobDataDetail> {
public int jobSequence;
public String jobReferenceId;
public String jobAddress;
public String jobScheduledDate;
public JobDataDetail() {
super();
// TODO Auto-generated constructor stub
}
public JobDataDetail(int jobSequence){
super();
this.jobSequence = jobSequence ;
}
public JobDataDetail(String jobReferenceId){
super();
this.jobReferenceId = jobReferenceId;
}
public int getJobSequence() {
return jobSequence;
}
public void setJobSequence(int jobSequence) {
this.jobSequence = jobSequence;
}
public String getJobReferenceId() {
return jobReferenceId;
}
public void setJobReferenceId(String jobReferenceId) {
this.jobReferenceId = jobReferenceId;
}
public String getJobAddress() {
return jobAddress;
}
public void setJobAddress(String jobAddress) {
this.jobAddress = jobAddress;
}
public String getJobScheduledDate() {
return jobScheduledDate;
}
public void setJobScheduledDate(String jobScheduledDate) {
this.jobScheduledDate = jobScheduledDate;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((jobReferenceId == null) ? 0 : jobReferenceId.hashCode());
result = prime * result + jobSequence;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JobDataDetail other = (JobDataDetail) obj;
if (jobReferenceId == null) {
if (other.jobReferenceId != null)
return false;
} else if (!jobReferenceId.equals(other.jobReferenceId))
return false;
if (jobSequence != other.jobSequence)
return false;
return true;
}
#Override
public int compareTo(JobDataDetail another) {
return this.getJobReferenceId().compareTo(another.getJobReferenceId());
}
}
List.indexOf() uses equals() method to compare objects.
In your case, you are assuming that two objects with same jobReferenceId are equals but your equals() method doesn't say so (because of the jobSequence test at the end of your method).
If you want to get an item from your list by one of its attribute, the easiest way would be using filter expression in Java 8:
JobDataDetail job = jobList.stream()
.filter(j -> j.getAttribute().equals(someValue))
.findFirst();
If Java 8 is not an option, I would go for a classic for loop iterating over the list.
I have removed jobSequence condition check from equals method and it's working.
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 currently have two classes Main and Command.
They are both inside of the package emerica.simple
So the classpath is emerica.simple.Main and emerica.simple.Command
In main I define a Boolean called spyblock
public class Main extends JavaPlugin{
public static boolean spyblock = true;
In command I am trying to access it and change it
public class Command implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
return true;
if (Main.spyblock == true) {
Main.spyblock = false;
}
else {
Main.spyblock = true;
}
}
else
{
return false;
}
}
Hoe can I change this code so it works? I am trying to toggle main.spyblock this the command "Spyblocks"
Your code for altering spyblock is not reachable because of
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
**return true;**
if (Main.spyblock == true) {
Main.spyblock = false;
}
else {
Main.spyblock = true;
}
}
highlighted line. just move this like
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
if (Main.spyblock == true) {
Main.spyblock = false;
}
else {
Main.spyblock = true;
}
**return true;**
}
Hope this helps
You have unreachable code :
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
return true;
//unreachable code
if (Main.spyblock == true) {
Main.spyblock = false;
}
else {
Main.spyblock = true;
}
}
That's why value of Main.spyblock doesn't change.
You returned your method just above your 2nd if i.e. return true;, that's why your if is not executing, you have to put return true; after your 2nd if-else condition.
If you just want to toggle it do it like this:
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
Main.spyblock = !Main.spyblock;
}
I don't fully understsand what you are trying to do, but currently your code won't compile properly.
Try changing it to the following
public class Command implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("spyblocks")) {
if (Main.spyblock == true) {
Main.spyblock = false;
}
else {
Main.spyblock = true;
}
return true;
}
return false;
}
You can also change your logic, making it a bit simpler, since you do not have to check for both conditions, since you are always toggling it. Therefore just always set it to the opposite of what it currently is.
Main.spyblock = !Main.spyblock;