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 4 years ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need help with a question I saw in my last exam.
Write the output of the execution of the following method by the call pX(7).
public static void pX(int x) {
if (x > 1) {
pX(x/2);
pX(x/2);
}
System.out.println(x);
}
I don't understand recursion when a method calls itself twice. I tried to solve problems with multiple recursion, but I just can't "invert" my mind in a way to multiple recursive thinking.
Can someone explain how multiple recursion works?
Is there any specific mechanism for understanding it?
Will writing a recursion tree or stack call on a blank list will help to understand it?
Is there any reading (like books or articles) about multiple recursion that's worth reading?
Recursion is when a method or function calls itself.
Multiple Recursion is when a method or function contains multiple self-references. This is when it gets a bit tricky. Lets take a look at your example.
You call px(7), and since the parameter is over the value of 1 as your condition checks for, it will enter that code block and encounter the first recursive call, dividing your parameter by half, px(7/2), which evaluates to px(3) (rounded down for integers).
Now that you've entered your first recursive call, lets put your original call on hold for a sec and focus on this new call of px(3). Your condition determines that x is still greater than 1, so we encounter our first recursion within this call. So we call ourselves again, dividing the parameter by half, px(3/2) which evaluates to px(1) (again, rounded down).
Now our condition will no longer pass, so there will be no recursive calls within this iteration, We will go directly to System.out.println(x); and print out the value 1
Back to where px(3/2) got called, the next line in that condition is to do it again. So we call px(3/2) again.
Still, our condition will not pass, so we will not call any more recursive calls and go directly to System.out.println(x);
And again, back to where that second px(3/2) got called. We've completed our condition block and can finally call System.out.println(3);
Here are your first three lines in the output, 1,1,3
It can be kind of tricky, but you need to focus, retain and follow the call stack to really get this down.
Related
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".
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 3 years ago.
Improve this question
Terminal
Java Code
Hello everyone.
I am having problems compiling my Java Code.. I am presuming it is because of a casting/promotinng error in the second method "method1".
If anyone could spot the errors and let me know that would be great!
Thank you in advance
Whenever you define a new variable, it is 'available' within some scope. For the vast majority of java variable definitions, that scope is 'lexical': Look for the nearest enclosing pair of brackets. Within that, it is visible. Outside, it does not exist.
On line 22 you define variable n1: int n1 = ...;. The nearest braces are on line 21 through at least 40 (the screenshot isn't wide enough) – certainly not line 12, where you reference it. So, at line 12, n1 simply does not exist. at all. That's one error explained.
Another is line 24: Line 23 returns. There is no way for the code to continue execution after that, and javac won't let you compile this: Line 24 is erroneous in that it is impossible to reach. I don't know how to fix it because your code is not clear; I don't know what you are trying to do here.
Perhaps you think 'return' is like 'export'; that's.. just not how it works. return returns from the method. Execution stops right then and there in that method and swaps back to the caller, and the method's value is whatever the expression you supply to the return statement calculates to.
It feels like you want to return 3 separate values from the method. That's not how java works: You can return only one. You can make this some sort of object (an array, or a new instance of a class you write) and in that way effectively 'return multiple values', but you have to package them up into a single thing to return.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a check in a loop where I have to check if the number of occurrence is less than 10 which could be written as either
if(occ < 10){
}
or
if(checkIfOccurencyIsLessThan10(occ)){
values.add(current+"0"+occ);
}
else{
values.add(current+occ);
}
I'm reading Clean Code a handbook of agile software craftsmanship, where they say a method should do the least amount, and code should be hacked up into more pieces. Is this necessary right here? I'm trying to get a better grasp on how long a method should be, and how much it should be doing.
It depends on if this condition is spread across multiple pieces of code, and if this check could change in the future to include checking additional edge cases. If both of those things are true or could be true, then sure, extracting the check to its own function is wise. However, I would definitely say you should rename the function to not specify the functions implementation, because that defeats the purpose of being able to change out the conditional, right? Naming it something like occurenceNeedsZero is a much more flexible solution. Because if you come up with other use cases that need checking you can add them to this function as well!
However, if your question is "should I always make a simple conditional check such as "is x < 10" into its own function, then I would say no. That would be overengineering, in my opinion. Functions should be used to 1) separate logical portions of code, 2) increase readability, or 3) extract small pieces of code that are spread across multiple locations and likely to change in the future, as it simplifies future refactoring.
There are probably more cases than those 3, but those are the big ones.
It's better to use a static final variable to store this 10, instead hard code.
If there are other places need to check if occ < 10, you need extract it as a method. Otherwise it is unecessary.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I didn't find any practical use of do-while loop. As a studied we don't have control over the do-while loop when it executes for the first time and everything which can be done with do-while loop, can be don with while or for loop (assuming).
My Question is: Is there any situation where we use a do-while loop, or any particular situation where it gives more reliable results as compared to for and while loops?
it's useful for repeating an action until it's correct
String input;
...
do
{
input = getInput();
} while(isValid(input));
to do that with another loop, you'd have to write input = getInput(); twice
do/while is precisely suitable when you always want to execute at least once, but you want to check whether or not to keep going at the end of the loop instead of at the start.
You can easily emulate it with a while loop, but sometimes the code becomes less clear that way. All three loop types can be emulated with each other, with more or less mess - but as all three are available, you should just pick the most appropriate loop for the job in hand.
I personally use both while loops and do/while loops less often than for loops, but sometimes a do/while is the most readable option.
Might as well say "I didn't find any practical use of for loop...everything which can be done with for loop, can be don with while loop (assuming)".
Technically you can replace any loop with literally any other loop given enough finangling with the loop guards and such. Some loops are just nicer to read than others.
do-while is primarily "better" if you want to perform an action at least once, e.g. asking for input, or getting some random value until it fits into some constraint. You can do such an action by performing the action once outside a "regular" loop and looping from there, but it's just neater to use do-while.
Do-while has generally better performance characteristics if the loop body must execute at least once. If you reformulate a do-while into a while/for, you add an extra evaluation of the loop exit condition.
Also, do-while(false) is usable as a structured alternative for deeply nested if conditions:
do {
if (!condition1)
break;
if (!condition2)
break;
if (!conditionN)
break;
// do something
} while (false);
instead of:
if (condition1) {
if (condition2) {
if (conditionN) {
// do something
}
}
}
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();