IF statement and few conditions in JAVA [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need to check 9 conditions for true or false and they need to be all true in one time.
How can it be possible checked, besides
if (condition1 && condition2 && condition3 ... && condition9) {
...
}
Think I used word "condition" right.

It is hard to know if you don't show more code than that.....
However, if I only have that piece of code, I can recommend three things:
1. If you have this information, start with the condition that is most likely to be false, that may improve performance..... more information here short circuit
2. Another thing, if you have all the conditions in an array, you can loop trough the array... Something like this:
public boolean testCondition(boolean conditionsArray[]){
for(int i = 0; i < array.length; i++){
if(!conditionsArray[i])
return false;
}
return true;
}
Post more code and I will try to improve my answer.
3. You might want to rethink about the data structures also. Probably something is not very clean in your design if you need to test for 9 given conditions like that (just probably).
Hope it helps.

Whenever I get into such a situation in code, I know I'm doing it wrong, and need to rethink my object structure.
However, just at the pure level of the question, as long as the conditions are in a collection of some kind, this will work:
boolean allTrue = true;
for (boolean condition : conditions) {
allTrue &= condition;
}
And then do the if on the allTrue variable. Note that I am assuming that the collection is not empty, or if it is, that should be regarded as a true condition.
Most likely in the real world you have to wrap these conditions in some kind of object with a common interface with a method that returns the boolean and use that, rather than having a collection of pure booleans.

Related

Java Related, regarding: If-Else, Do-While, Try-Catch [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am in my first semester of a Java Course. I am struggling to understand how I put exclusiveness on a statement. I am writing a Class for an Object Couch. I have tried to build a well formed class, but for the outcome from my main, in the console it must only have 4 or 8 legs on the couch. There is no user input as I am hard coding the variables, but I want to be sure that if I hard code for 5 legs it will stop me or an error message will pop up. Any suggestions?
public void setNbrLegs(int nbrLegs){
if ((nbrLegs == 2) || (nbrLegs == 4)){
this.nbrLegs = nbrLegs;
}
}
I tried putting an "else" with a message that that number is bad, but what is did was bypass my error message and just insert the incorrect number ofLegs as 5.
Consider looking for the opposite: a condition where you must fail. From there, you can use runtime exceptions to ensure a few things:
The invalid state is not applied
A developer passing this invalid state will get an exception, and have a clear reason to fix their code
You no longer have to worry about invalid state further on in the method (i.e. legs will only be 2 or 4 further on).
In doing so, your method may end up looking like this:
public void setNbrLegs(int legs) {
if (legs != 4 && legs != 2) {
throw new IllegalArgumentException("Can only have 2 or 4 legs");
}
this.nbrLegs = legs;
}
This preconditional checking is also good to do early in your methods (fast-fail), as it will prevent excess work being done for a method that will only "fail".

Comparing LocalTime returns true, even tho debugger evaluates to false [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
So, I am currently working on a function that checks if a given LocalTime is inside a range. All good, and the equivalent for LocalDateTime works without an issue.
So, my code right now looks like this:
public boolean isInRange(LocalTime time){
return (time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime()) &&
time.isBefore(roundedEndTime.toLocalTime());
}
It has some specifics for my business logic, but thats not part of the issue. I also have accompanying junit tests, that check if the logic works as intended. Again, the inRange(LocalDateTime time) function works flawlessly.
But using my tests, with the same time I use for the LocalDateTimeverification, they fail, as they somehow return true. I've started debugging, and can't quite believe my eyes, which explains the true && falsecheck:
For whatever reason, evaluating the two statements separately shows the expected behaviour, but combining them, returns true.
Your function of
public boolean isInRange(LocalTime time){
return (time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime()) &&
time.isBefore(roundedEndTime.toLocalTime());
}
Is checking whether
time is after roundedStartTime
or
time equals roundedStartTime
and
time is before roundedEndTime
Looking at the Java operator precedence table we can conclude that && has a precedence of 4, while || has a precedence of 3. As a result, your condition is checking whether (time equals roundedStartTime and before roundedEndTime) or (time is after roundedStartTime).
So, when your time is after roundedStartTime and after roundedEndTime, that is, it's later than the whole range, the condition will still be evaluated to true, because the first operand of || evaluated to true. To fix it, you will need to wrap paranthesis around your ||, so your logical expression will evaluate to
(time >= roundedStartTime) and (time < roundedEndTime)
Fix:
public boolean isInRange(LocalTime time){
return ((time.isAfter(roundedStartTime.toLocalTime())) || time.equals(roundedStartTime.toLocalTime())) &&
time.isBefore(roundedEndTime.toLocalTime());
}

Understanding a coding challenging in finding the first duplicate value in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)

How does a return statement work in recursion? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When working with recursion I realized I'm not sure how the return statement works. Does it stop and return true when target.contains(key) returns true or does it fall out and return false, because of the line below? Does the previous iterations of the method get finished so that it instead return false?
The program creates passwords and this method is called to check that the password contains one of the required fields, such as upper case letters, symbols or numbers. It's called with 4 separate sources and they are then used to tell the program to keep the password or to create a new one if it doesn't meet the required standards. I've done this program for fun to refresh my memory of Java, it's not a real program that anyone will ever use.
private static boolean containsKeyword(String target, String source, int placement){
String key = String.valueOf(source.charAt(placement));
if(target.contains(key))
return true;
if(placement==0)
return false;
containsKeyword(target, source, placement-1);
return false;
}
You seem to be missing the whole point of the recursion step.
Change this:
someFunc(a, b, nbr-1);
return false;
To this:
return someFunc(a, b, nbr-1);
By the way, recursively calling this function with the exact same data (the strings a and b) is pointless.
There must be something else that you want to call this function with (perhaps sub-strings of a and b).
Your method will always return false if it doesn't get into the first if. You need to change this:
someFunc(a, b, nbr-1);
return false;
to
return someFunc(a, b, nbr-1);
Maybe if you update your question with what exactly you are trying to do, you will get a more targetted answer that will help you understand the recursion better.

Dead code in Java/Android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
is there a way to tell the compiler in Java or Android to not remove some statements in code -which are intended to clean up variables after use to prevent any data remnant in ram-??
would creating a dummy method solve this issue??
these statements basically set the variables to their type-based initial values..
Thanks in advance!
The code that you describe is not dead code.
Dead code is code that will never execute.
Here is an example:
private int secretSchmarr;
public boolean blammo()
{
boolean returnValue;
secretSchmarr = calculateSecretValue();
returnValue = useSecretValue(secretSchmarr);
secretSchmarr = 99; // this is not dead code.
return returnValue;
secretSchmarr = 98; // This is dead code because it can never execute.
}
I answer under the odd assumption that you have a good reason to believe that the code is still useful even though it is dead.
Store the value false in some obfuscated form that the compiler can't understand. Then, conditionally branch to that code using your obfuscated value. The compiler will not know it is dead, so it will not be removed.
I'll use a file for my example, but it is probably not the most efficient way. Say your code that the compiler thinks is dead code was in a function called myCode(). Assume that fin is reading from a file that only contains false followed by EOF
if(Boolean.parseBoolean(fin.next()))
myCode();

Categories

Resources