I wrote a 'setX' method in Java that says that if x value ( (x,y) ) is negative, the value of x wont be change, and the main() will continue as usual.
void setX (int num)
{
if (num < 0)
break;
else
{
_x = num;
}
}
Am I right ?
I am not sure because of the break issue, is the break statement just break from the current method ?
thnx
break is used only in loops (while, for).
If you want to exit the method, use return instead.
Perhaps you meant
public void setX(int x) {
if (x >= 0)
_x = x;
}
you should use return. break is to break loops.
Use return; here. break is used to break out of loops.
According to the Java tutorial, break is for use with switch, for, while, and do-while loops. It doesn't go in if statements. For a switch the break keeps the switch from falling through to the next case, which it would otherwise do. For loops it stops looping regardless of the loop guards.
A break statement can either be unlabeled, in which case it goes to where control would normally resume after the switch or loop, or labeled, in which case it goes to the label (almost as if it were a goto with strict constraints on where it can come from).
To get out of the current method, use return. A return with no value is the proper statement to leave a void method.
That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;
I think your intention might be a bit clearer if your logic was reversed;
void setX (int num)
{
if (num >= 0)
_x = num;
}
Related
I made what I think is an example of recursion. Is this acceptable? It's not for a project or anything, my professor is just awful so I try to teach myself.
public void theCat() {
int i;
for (i = 0; i <= 50; i++) {
System.out.println(i);
if (i == 10) {
theCat();
}
}
}
Yes, that is recursion. However, it will be infinite since you never stop it.
What you should do is to have a base case where you check if it is time to stop the recursion. You would also have a reduction step, that will converge the parameter towards the base case, like so:
public int theCat(int i) {
if (i => 50)
return i;
else
return theCat(i + 1);
}
To show the effectiveness of this, have a look at a recursive factorial method:
private long factorial(int n) {
if (n == 1)
return 1;
else
return n * factorial(n-1);
}
Here, the base case checks if we are trying to calculate 1! and in that case returns 1. This is the case where we no longer need to recursively call the method. Instead, we walk backwards along all of the method calls we have made to calculate the final answer:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
This will cause overflow. All recursion should have some kind of base case for exiting so that it does not go infinitely.
Additionally all recursive functions usually receive some kind of an int or some value so that they can use that value in the base case and exit. So for your example I would send int i as an argument into cat and stop when i == 50
Yes and no. Technically this is an example of recursion. But this will never terminate. Normally there is some parameter passed into a recursive method so that it can recognize a "base case" which will not recurse.
Yes, but you must have flag that determine exit from your method, otherwise you catch StackOverFlowError
That will cause a stack overflow as the recursive call is infinite.
We can define recursion in this way:
1. we start with a method that has a specific state
2. inside this method the method itself is called, but the call changes the state of the method
3. the method has a base case (a case where if a method reaches this state it no longer calls itself recursively).
How do I make this work? It says that I need to add a return statement but I have one.
public boolean clockFactCheck(int a, int b){
for (int i = 0; i <= 276; i++){
for (int h = 0; h <= 55; h++){
if (a == i + 186 && b == h + 133){
return true;
} else {
return false;
}
}
}
}
The code provided may not reach one of the returns for any input a,b and that's what the compiler is complaining about.
Actually in your case the if-else will be reached with the very first iteration - unfortunately something which the compiler cannot deduce. Therefore, it goes the save way and issues this error.
Comment: Therefore, in your loop seems not to make much sense since it will not iterate at all but stop within the first iteration i==0 and h==0. Did you meant to code something like that?
You don't have a return statement after the for loop but even then h++ is dead code becaue it will never get past the first iteration.
Place the return statement outside the loop. (declare a boolean in your function, modify it and return it at the end)
My guess is that the compiler is not clever enough to figure out that there is no codepath around the loops.
If this is real code, simplify it to
return (a == 186 && b == 133);
If this is not the real code, there is probably another path that does not return (if you made an error pasting), or there really is a compiler bug or limitation. At one point, the halting problem bites you, and the code is too complex for the compiler to figure out.
In the latter case I would place a
throw new RuntimeException(
String.format("should never get here (a = %d, b = %d) !",a,b));
at the last statement.
That makes both the compiler happy and does not introduce an "undefined" return value for a case that should either never happen, or if it does, has not been thought of.
Oh yeah my bad, I'm sorry this was a stupid question it was 5am when I posted this. I figured out the answer to my problem. If you made the same stupid mistake as me here is the fix
public boolean clockFactCheck(int a, int b){
for (int i = 0; i <= 276; i++){
for (int h = 0; h <= 55; h++){
if (a == i + 186 && b == h + 133){
return true;
}
}
}
return false;
}
Java requires every path return a value. The compiler could not judge if the circulation will return a path. If your code is like this:
public boolean add(){
for(int i=0;i<100;i++)
if(i==5000)
return true;}
the function add will not return a value. Instead, an error will occur.
I would like to ask you guys a question. You see, I know what a for-loop is for but can someone please maybe explain how one works, just to help me get my head around it, an example is:
for(int i = 0; i < 10; i++) {
System.out.println("hello");
}
Now obviously that will just print Hello 10 times into the console but that's besides the point, I want to know how the for-loop works.
Sorry if i have confused anyone asking this - Shaun
The for loop in your example is more or less equivalent to this:
int i = 0;
while (i < 10) {
System.out.println("hello");
i++;
}
The only difference is that with your for loop, the variable i exists only within the scope of the loop.
Every for loop can be transformed into a while loop using this same pattern.
for (init; test; continuation) {
// loop body
}
becomes:
init;
while (test) {
// loop body
continuation;
}
Again, the only difference will be with the scope of any variables declared in init.
The for Statement
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Well, this is how it is set up:
for (a; b; c)
"A" is something that is done at the beginning of the loop. It can actually be left out if necessary, like this:
for (; b; c)
"B" must be a true or false statement (like i<10, it either is or it isn't). Once "b" is no longer true, the loop stops.
"C" is something that is done at the end of the loop.
(In the process of writing my original question, I answered it, but the information might be useful to others, and I thought of a new question)
For instance:
int x;
if (x = 5) { ... }
Creates an error:
Type mismatch: cannot convert from int to boolean. (Because assignment doesn't return a
boolean value)
However,
int x;
if ((x = 5) == 5) {
System.out.println("hi!");
}
will print out "hi!"
And similarly,
String myString = "";
if ((myString = "cheese").equals("cheese")) {
System.out.println(myString);
}
prints out "cheese"
Sadly,
if ((int x = 5) > 2) { ... }
does not work with an in-line declaration. How come? Can I get around this?
Sadly,
I suspect that most Java developers would heartily disagree with that sentiment ...
if ((int x = 5) > 2) { ... }
does not work with an in-line
declaration. How come?
It does not work because a declaration is not a Java expression, and cannot be used in an Java expression.
Why did the Java designers not allow this? I suspect that it is a combination of the following:
Java's syntactic origins are c and C++, and you cannot do this in C or C++ either,
this would make the Java grammar more complicated and the syntax harder to understand,
this would make it easier to write obscure / cryptic programs in Java, which goes against the design goals, and
it is unnecessary, since you can trivially do the same thing in simpler ways. For instance, your example can be rewriten this to make the declaration of x to a separate statement.
Can I get around this?
Not without declaring x in a preceding statement; see above.
(For what it is worth, most Java developers avoid using assignments as expressions. You rarely see code like this:
int x = ...;
...
if ((x = computation()) > 2) {
...
}
Java culture is to favour clear / simple code over clever hacks aimed at expressing something in the smallest number of lines of code.)
Your x only exists within the scope of the assignment, so it's already gone by the time you get to > 2. What is the point of this anyway? Are you trying to write deliberately unreadable code?
Your best way to get around this is to declare x in a scope that will remain valid throughout the if statement. Seriously though, I fail to understand what you're doing here. Why are you creating a variable that is supposed to disappear again immediately?
if ((int x = 5) > 2) { ... }
Yes this will not compile because you can't declare variables inside the condition section of if clause
The > test will work fine, as long as you declare the int outside of the if condition. Perhaps you are simplifying your condition for the sake of brevity, but there is no reason to put your declaration in the condition.
Can I get around this?
Yes, declare your var outside the condition.
Because you didn't declare the int separately as you did in the == test.
jcomeau#intrepid:/tmp$ cat /tmp/test.java
class test {
public static void main(String[] args) {
int x;
if ((x = 5) > 2) System.out.println("OK");
}
}
In Java, for() allows initialization code, but if() doesn't.
You can't declare the variable in condition section. For example
for(int i = 0; j < 9; i++){...}
is completely valid statement. Notice we declare the variable in for but not in a condition clause, now look at this,
for(int i = 0; (int j = 0)<9; i++){...} // Don't try to make logical sense out of it
not allowed.
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