Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean in the correct way.
public Space fire()
{
System.out.println("Hi");
}
public boolean hitRateAnalysis()
{
if (HitShipPercentage < 50 && Shots!=0)
return true;
else{
return false;
}
}
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.
This will call the fire method correctly:
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots != 0){
fire();
return true;
}
return false;
}
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space. I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.
public void fire() {
System.out.println("Hi");
}
public boolean hitRateAnalysis() {
if (HitShipPercentage < 50 && Shots!=0) {
fire();
return true;
}
return false;
}
Related
How is it possible to set an object and method in a condition? I understand that, if the animal is over 50kg it weighs too much. But how about if an animal is hangry, need Love and feel boring return the method feelingNegative()?
I don't know how to set it. But after an animal sleeps, it is hangry. A thought would be:
Animal {
if (hangry == false && needLove == false && boring == false) {
return feelingNegative();
}
}
still don't know how to set it.
public class Animal {
private boolean needLove;
private boolean hangry;
private boolean boring;
private int kg;
public boolean sleep() {
return hangry = true;
}
public boolean watchTv() {
return needLove = true;
}
public void feelingPositive() {
System.out.println("I feel good");
}
public void feelingNeutral() {
System.out.println("Someting is missing...");
}
public void feelingNegative() {
System.out.println("I need love, food and fun!");
}
public void weight(int kg) {
if(50 < kg) {
System.out.println("You ate way too much");
}else {
System.out.println("You need to eat more");
}
}
}
The methods you are calling don't return anything (they are void). Just remove the return. And use boolean negation (!) instead of == false. Like,
if (!hangry && !needLove && !boring) {
feelingNegative();
}
The Method feelingNegative() doesn't return anything (Void). So you just have to define a method that call feelingNegative() when all the conditions are satisfied.
public void myMethod ()
{
if(!hangry && !needLove && !boring)
feelingNegative();
}
So I have this simple boolean method for checking whether my game has ended. In the main method, I then have a big loop that starts with the statement while (isGameEnd() == false) {...}. This loop never seems to break, even when one, two or all of the conditions in the method becomes true. I don't get it.
public static boolean isGameEnd() {
if (lives == 0 || steps == 0 || isMazeCompleted()) { return true; }
else { return false; }
}
The use of static in the function definition is a red flag to me. If a class is defined with default field values, then those default values will be what is checked rather than the particular implementation of the class:
class Game {
int lives = 3;
int steps = 10;
public boolean isMazeCompleted() {
return false;
}
public void doStuff() {
lives--;
}
public static boolean isGameEnd() {
if (lives == 0 || steps == 0 || isMazeCompleted()) {
return true;
} else {
return false;
}
}
}
public static void main(String[] args){
Game a;
while(!a.isGameEnd()){ // check 'isGameEnd' for the static class
a.doStuff(); // This does *not* update the static class
}
}
Most Java editors will complain about the use of static functions in a non-static context, so will suggest Game.isGameEnd() instead of a.isGameEnd(), which makes it a bit more obvious to the programmer where the error is.
I don't understand why I am getting "return statement missing".
Here is the image with the code:
In your 2nd and 3rd if conditions there are no returns. Instead of your else, just return false.
So it reads:
public class isTrans {
public static boolean isTrans(String s,String t) {
if (t.length()==1 && (s.charAt(s.length()-1))==t.charAt(0)){
return true;
} else if (s.charAt(0)==t.charAt(0)){
return isTrans(s,t.substring(1));
} else if (s.charAt(1)==t.charAt(1)){
return isTrans(s,t.substring(1), t);
}
return false;
}
}
In this case you have to return in all the conditions or return at the end of the method.
if(/*...*/) {
return true;
}
else if(/*...*/) {
return isTrans(/*...*/); // return whatever isTrans returns
}
else if(/*...*/) {
return isTrans(/*...*/); // here too
}
else {
return false;
}
You have to return the result of the function execution in your else if, so the recursion works properly. Like this:
return isTrans(s, t.substring(1))
I need to compare two Objects. If there is a difference I need to log it corresponding to particular difference and return the true.
For example:
private boolean compTwoObjects(Object objA, Object ObjB) {
if(objA.getType() != objB.getType()) {
logTheDifference("getType is differing");
return true;
}
.
.
.
// Now this could invoke other composite methods
if(checkFont(objA.getFont(), objB.getFont()) {
logTheDifference("Font is differing");
return true;
}
}
private boolean checkFont(Font fontObjA, Font fontObjB) {
if(fontObjA.getBold() != fontObjB.getBold()) {
logTheDifference("font bold formatting differs");
return true;
}
.
.
.
if(fontObjA.getAllCaps() != fontObjB.getAllCaps()) {
logTheDifference("font all caps formatting differs");
return true;
}
.
.
.
if(checkBorderDiff(fontObjA.getBorder(), fontObjB.getBorder())) {
logTheDifference("border diff");
return true;
}
}
private boolean checkBorderDiff(Border borderObjA, Border borderObjB) {
if (borderObjA.getColor() != null || borderObjB.getColor() != null) {
if (!borderObjA.getColor().equals(borderObjB.getColor())) {
logIt("border color differing");
return true;
}
}
if (borderObjA.getDistanceFromText() != borderObjB.getDistanceFromText()) {
logIt("distance of the border from text or from the page edge in points differing");
return true;
}
if (borderObjA.isVisible() != borderObjB.isVisible()) {
logIt("border visibility differing");
return true;
}
if (borderObjA.getLineStyle() != borderObjB.getLineStyle()) {
logIt("line style differing for border");
return true;
}
if (borderObjA.getLineWidth() != borderObjB.getLineWidth()) {
logIt("border width in points differing");
return true;
}
if (borderObjA.getShadow() != borderObjB.getShadow()) {
logIt("border shadow differing");
return true;
}
}
//And it is going like this.
My problem is I want to avoid multiple if statements in the methods. Also I want to log the messages corresponding to particular difference.
I have read few similar type of problems on stackoverflow solved either by command pattern or HashMap. But they don't include comparisons in that.
I want to refactor my code to get rid of series of if's.
Have a system of comparators, backed by generics. Every comparer will also know what is next in line. For example:
interface IComparer<T> {
boolean areDifferent (T first, T second);
}
class FontComparer implements IComparer<Font> {
#Override
public boolean areDifferent(Font first, Font second) {
// Compare fonts start
// ..
// Compare fonts end
return new BorderComparer().areDifferent(first.getBorder(), second.getBorder());
}
}
class BorderComparer implements IComparer<Border> {
#Override
public boolean areDifferent(Border first, Border second) {
//Do border comparison alone
return false;
}
}
You could setup a comparer chain now, and bail out when comparison fails. Otherwise, comparison goes to the comparer next in the chain.
The client code will finally look like:
Object one = new Object();
Object two = new Object();
new ObjectComparer().areDifferent(one, two);
Have you considered enums?
private enum FontCmp {
Bold {
#Override
boolean cmp(Font a, Font b) {
return a.getBold() != b.getBold();
}
},
AllCaps {
#Override
boolean cmp(Font a, Font b) {
return a.getAllCaps() != b.getAllCaps();
}
},
Border {
#Override
boolean cmp(Font a, Font b) {
return BorderCmp.compare(a.getBorder(), b.getBorder());
}
};
// Each enum has one of these.
abstract boolean cmp(Font a, Font b);
// Compare them all and log any failures.
static boolean compare(Font a, Font b) {
for (FontCmp c : FontCmp.values()) {
if (c.cmp(a, b)) {
logIt("FontCmp-" + c + " failed");
return false;
}
}
return true;
}
}
You could also use reflection as described here. Also look into introspection as described here
Fundamentally you are trying to do a series of comparisons, so there is little choice but to do a series of comparisons.
What you could do is define an interface/enum/abstract class which is a FieldChecker. That FieldChecker would have an abstract method implemented differently in each FieldChecker:
String performCheck(Font a, Font b) {
if (DO CHECK HERE) {
return "failure message";
}
return null;
}
Then your check function just becomes:
for (FieldChecker fc: fieldCheckers) {
String res = fc.performCheck(a,b);
if (res != null) {
return res;
}
}
return "All ok";
I need help on how to return a boolean method in java. This is the sample code:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}
else {
addNewUser();
}
return //what?
}
I want the verifyPwd() to return a value on either true or false whenever I want to call that method. I want to call that method like this:
if (verifyPwd()==true){
//do task
}
else {
//do task
}
How to set the value for that method?
You're allowed to have more than one return statement, so it's legal to write
if (some_condition) {
return true;
}
return false;
It's also unnecessary to compare boolean values to true or false, so you can write
if (verifyPwd()) {
// do_task
}
Edit: Sometimes you can't return early because there's more work to be done. In that case you can declare a boolean variable and set it appropriately inside the conditional blocks.
boolean success = true;
if (some_condition) {
// Handle the condition.
success = false;
} else if (some_other_condition) {
// Handle the other condition.
success = false;
}
if (another_condition) {
// Handle the third condition.
}
// Do some more critical things.
return success;
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
System.out.println("password do not match");
}
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
addNewUser();
return true;
}
}
You can also do this, for readability's sake
boolean passwordVerified=(pword.equals(pwdRetypePwd.getText());
if(!passwordVerified ){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
}else{
addNewUser();
}
return passwordVerified;
Best way would be to declare Boolean variable within the code block and return it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.