I have:
boolean cond=false;
if(!gto)
cond=(in-Math.pow(base, pot)<0);
else
cond=(in-Math.pow(base, pot)>=0);
while(cond)//Pos1
...
This work not in the desired way, because pot is changed within the while-loop.
Of coure I could write a boolean-valued method, but I wonder, if there is a way to force Java to evaluate cond just when reaching Pos1?
while((in-Math.pow(base,pot<0&&!gto)||(in-Math.pow(base, pot)>=0&>o))){
//do sth
}
is this what you want?
For cleanliness and maintainability, use a method, assuming you have Java 8 available, you could also use a lambda predicate as shown below:
Predicate<Boolean> checkCondition = (boolean gto) -> {
double someCalculationResult = in - Math.pow(base, pot);
if (!gto) {
return someCalculationResult < 0;
}
return someCalculationResult >= 0;
}
while (checkCondition(gto)) {
...
}
Or inline the condition (see answer by #kleopi) if this is some write and forget about it code.
If the value of gto does not change in the loop and the loop body is not complex, then you could just write two separate loops for the individual cases:
if ( gto ) {
while ( in - Math.pow(base, pot) >= 0 ) {
// Do stuff
}
} else {
while ( in - Math.pow(base, pot) < 0 ) {
// Do stuff
}
}
If possible, you could then also move the loop body into a separate method and call it from both loops.
Related
Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh
i saw how to break the loop (using label and break the label) .. but i want to break the first for loop depends on the second for loop :
for example :
public class HelloWorld {
static private int i;
public static void main(String[] args) {
int y = 20;
for (; y <= 30; y += 2)
{
System.out.printf("value of increamented y Value is %d\n", y);
increamentiValue();
}
}
private static void increamentiValue()
{
i = 0;
for (; i <= 5; i += 2) {
System.out.printf("value of i is %d\n", i);
}
}
}
for instance here i want to break the "y" loop depends on the number of iteration in "i" loop ..
for ex:
i want to break "y" for loop if the number iteriation in "i" loop is equal to 0 .. because in my program "i" checks the error ... in my ysytem error may occur any "i" .. if two times i dosnt have error (i==0) i want to break the "y" loop.
EX :
if
At y= 22 , i ==0; (no error occurs)
at y= 23 , i ==0; (no error occurs)
i dont want to proceed till 30. i want to break y loop .
Have increamenti_Value return a value that main uses to terminate the loop.
Separately, though, using an instance variable (i) in the for loop in increamenti_Value is a very suspect thing to do. It's also quite odd to use a for loop, leave out the initializer clause, and yet set the initial condition on the line above.
Have the incrementi_Value return the value of i and check that value in your y loop.
incrementi_Value == 0 ? break : continue;
Change private static void incrementi_Value -> private static int incrementi_Value
then place a return i; when you want to return the current value of i.
Instead of increamenti_Value() being void, make it return boolean - true if the caller should break, false otherwise:
private static boolean increamenti_Value() {
// return true if you want the caller to break
}
And instead of calling it like you are, call it like this:
if (increamenti_Value())
break;
Note that a called method having knowledge of when the caller should do something doesn't seem like a good design. You may want to reconsider your logic.
I just got a task asking me to do repeated addition from 1 to 21, as follows :
1,4,6,9,11,14,16,19,21
and get the total.
I tried this code but it returned to be a +2 addition, and it even bypass the prerequisite of bil<=21
public class test
{
public static void main(String[]args)
{
int bil=1;
long total=0;
boolean mult = true;
for(bil=1; bil<=21;bil++)
{
if(mult=true)
{
bil+=1;
mult=false;
}
else if(mult=false)
{
bil+=2;
mult=true;
}
System.out.println(bil);
total=total+bil;
}
System.out.println("----+");
System.out.println(total);
}
}
(if it's TL;DR)
Basically the request is 1+4+6+9+11+14+16+19+21=?
I can't seem to get these code to work, please help me?
EDIT : Thanks guys I got it now :D
You need boolean mult = false; so that the first time the loop runs, bil is incremented by 3 and not 2.
First, you are not comparing your boolean with ==. Therefore, every time the for() loop executes, the first block will be the one that enters since mult = true will always store true in mult... and then qualify that if() block to run.
If this assignment wasn't intentional, then you need to change it to == and also put some logic in your loop to toggle mult appropriately.
Basically when it runs through the first loop it only adds one because of the state of the boolean but also there should be an == operator to check instead of just an =
Try this:
for (bil = 1; bil < 21; bil++) {
if (bil % 2 == 0) { // If bil is divisible by 2, then add 2
bil += 2;
continue;
}
bil += 3;
}
I've got a problem that seems easy to solve, however I'm not sure on the syntax.
I need to have an if/else statement run, but I'm not sure on how to set the conditions correctly.
Bad code:
if (float_a = float_b or is within +-2 of it) {
do this
}
else {
do that
}
What's the simplest way of accomplishing this?
You can use Math.abs:
if (Math.abs(float_a-float_b) <= 2) { ... }
This means "if the absolute difference between a and b is within 2...".
if(Math.abs(float_a - float_b) <= 2) {
//do this
}
else {
//do that
}
let say my code look like below
for(..)
for(..)
for(..){
break; //this will break out from the most inner loop OR all 3 iterated loops?
}
Your example will break out of the innermost loop only. However, using a labeled break statement, you can do this:
outer:
for(..)
for(..)
for(..){
break outer; //this will break out from all three loops
}
This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:
A break statement with no label
attempts to transfer control to the
innermost enclosing switch, while, do,
or for statement of the immediately
enclosing method or initializer block;
this statement, which is called the
break target, then immediately
completes normally.
Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.
class Loop {
public void loopForXx() {
untilXx();
}
private void untilXx() {
for()
for()
for()
if(xx)
return;
}
}
From the most inner loop :)
int i,j,k;
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
for(k = 0; k < 2; k++)
{
printf("%d %d %d\n", i, j, k);
break;
}
Will produce :
0 0 0
0 1 0
1 0 0
1 1 0
You should take a look here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))
boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
for (int j = 0; j < 10 && !exit; j++) {
exit = true;
}
}
this is in my opinion more elegant than a break..
Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).
Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.
This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:
boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {
if (values.get(i).equals(targetValue)) {
targetFound = true;
}
}
if (!targetFound) {
// handle lookup failure
}
Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.
I sometimes use this solution, which I think is more concise and readable:
lookup: {
for(Value value : values) {
if (value.equals(targetValue)) {
break lookup;
}
}
// handle lookup failure here
}
I think breaking (no pun intended) the rule here results in better code.
it will breake from most inner loop,
if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop