My code is below:
public int workTimeSum(list of parameter){
int i=0,sum=0,flag=-1;
boolean b=true;
Stack<NonOverlapIntervals> str;
if(st.size()!=1){
b=recursiveCheck(non_overlap_list,st,Ioj);
if(b==false){
st.pop();
}
System.out.println("now size is:"+st.size());
}
str=(Stack<NonOverlapIntervals>) st.clone();
System.out.println("Stack is ss");
while(!str.empty()){
System.out.println(str.pop().self_id);
}
if(b || st.size()==1){
for(NonOverlapIntervals obj:non_overlap_list){
i++;
if(obj.id==ids){
if(st.size()!=1 && object_Present(st,obj)){
continue;
}
else{
st.push(obj);
sum=workTimeSum(non_overlap_list,obj,st,obj.self_id,i);
if(sum_max<sum)
sum_max=sum;
}
}
}
flag=1;
}
else{
return 0;
}
Above is a recursive code.
What you need to see in the above code is only sum, sum_max variable.
I am computing the sum and checking if it's greater than sum_max each time a sum is computed.
But as I have initialised sum_max to zero after each call my sum_max becomes 0;
The problem is eliminated if I declare sum_max as global variable.
But i am not allowed to use global variable.
I also tried passing sum_max a parameter of the recursive function but that won't work.
You can initialize the variable without needing a second method if you just check to see if it is null if so, initialize it and pass it to the next method (so it will be initialized)
//very basic endless example
public void myRecursiveMethod(Object var){
if (var==null){
var = new Object();
}
myRecusivemethod(var);
}
I think the answer lies in the way you have phrased the question. You misunderstand: you don't initialise a variable while you are recursing. You only initialise it once.
To do this, it may sometimes be helpful to create another method for the first step ("base case") of the recursion, which does the initialisation.
However, the code you posted doesn't actually match what you describe to be the case. In the code you posted, you don't initialise sum_max at all. So I'm confused.
Related
I am in a book with this code. I do not know which command the ''depth'' word is used for what purpose. I have found a few results but I do not understand what is still. I know java language but i am learning c ++ new.I wanted to know if there is something like this in Java.
if (depth() != otherStack.depth())
{
return false;
}
else
{
for (int n=0; n<depth(); n++)
{
if (!list[n].equals(otherStack.list[n]))
return false;
}
}
From the code snippet you posted, depth seems to be a method defined in the class whose instance is the otherStack variable. Here depth() probably returns the size of the stack.
The line depth() != otherStack.depth() compares the size of the Stack instance to the size of another Stack instance.
Currently on the chapter in my book where we talk about for loops and loops. I have sometimes come across an issue where the method needs me to return something. For example consider my code
below. Basically the exercise is to get all the factors in ascending order. Now heres the issue
As you can see I need a return statement outside of the for loop. Now I guess my book didn't exactly explain this properly, or I didn't understand the concept
of return properly in java, but does our return statement always have to be in the most outer indentation if you will?
The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this?
Whats a good counter-action?
Ever since I started learning loops and for loops, I have been having trouble understanding this. I guess I could just system.out.println(i) instead of returning it? But then what should I return? I could also make it a void type, and then make another method to print it, I guess?
class factors{
private int num;
public factors(int num)
{
this.num = num;
}
public int getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
return i;
}
}
// I NEED TO PUT A RETURN STATEMENT HERE
}
}
public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
System.out.println(fact.getFactors());
}
}
IT WORKS NOW ( I dont particularly like my solution)
class factors{
private int num;
public factors(int num)
{
this.num = num;
}
public void getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
System.out.println(i);
}
}
}
}
public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
fact.getFactors();
}
}
The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this?
Java lets you do that. There is nothing wrong with returning inside the loop upon reaching the condition.
Java allows you to have multiple return statements, so adding another return 0; after the loop is allowed.
Java returns once it hits the first return statement, and other return statements are not executed (the method isn't executed anymore) (except for some rare edge cases with try-catch and return, but thats another story entirely).
But why is it required?
Java requires that for all possible paths there exists a return with the proper type. Even if you yourself can proof mathematically that the path Java complains about is never taken, the compiler might not be able to prove that the path is not possible at runtime. So you simply need to add an return there with a dummy value.
In your concrete example, there is a condition in which the loop gets never executed. If num <= 0, then the loop condition is never satified and the entire loop body is skipped. Without the return,the method is invalid, because you can't return nothing from an method with return type int.
So, in your example, the compiler is actually smarter then you, and prevents you from making a mistake - because it found the path you thought wouldn't occur.
new factors(-1).getFactors(); // you don't check the passed value at all ;)
From your comments, it seems that you want to return all factors. In java, you return once, and only once, from a function. This means you have to aggregate the results and return a List or array of values:
public List<Integer> getFactors(int num) {
List<Integer> factors = new ArrayList<>();
for (int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
factors.add(i);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new factors(20).getFactors());
// prints a comma-separated list of all factors
}
does our return statement always have to be in the most outer indentation if you will?
No.
However, all potential code paths must return something. Consider this structure:
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
return i;
}
}
What happens if num is a value where the loop itself is never entered? Or what happens if the if condition is never satisfied? No return statement would ever be encountered, which is invalid.
The compiler has to guarantee that the method will return something, under any and all potential runtime conditions. So while it's perfectly valid to return from within the loop, you also must provide logic for what to return if that return statement is never reached.
Java doesn't let you do that because what happens if the if (num % i == 0) is never true?
The methods return type is int, so it has to return an int. And it's possible that the if statement could be false, not every condition is covered with a return statement.
So if you wanted to you could return something like -1, or another invalid value. Then you know that the function didn't find what it was looking for.
Problem
I want to be able to split up a for loop into a method, then put the for the method in the for loop to make it easier to read. Below demonstrates this:
Example.java
for(int member = firstMember; member < arrayOfMembers.length; member++) {
[...] other code
}
Should be refactored to:
Solution Example:
private boolean eachMemberInList() {
return int member = firstMember; member < arrayOfMembers.length; member++);
}
public static void main(String[] args) {
for(eachMemberInList());
}
Is this possible?
No, you cannot return or otherwise manipulate a for loop as if it were an object in Java.
However, what you're attempting to do is unnecessary. You can use an array directly in an "enhanced" for loop, since Java 1.5.
for (int member : arrayOfMembers) { ... }
It is more concise than attempting to create a method to manipulate a for loop, and it is even more concise than the standard for loop you're attempting to replace.
What you're talking about is turning a for loop, into a while loop.
for (; true; )
is equivalent to
while (true)
So, you're solution could be viewed as
while (someFunctionIsTrue()) {}
Don't want to get into religious debates here, but generally, if you're iterating over an array of objects, you really do want to use a for lop. Not necessarily because it's any different than a while loop using your solution, but because it's idiomatic. When a developer (an experienced developer) sees a for loop, the fact that you chose a for loop tells them something. It says, hey, I'm iterating over the objects of a container. What a while loop says, is that there is some condition, and while that condition is true do something.
While loops and for loops are identically in capability. By using them idiomatically, you can communicate your code more concisely and clearly. For example:
int index = 0;
while (index < array.size) {
doSomethingWithArrayElement(array[index]);
index++;
}
This is not concise. The hanging variable declaration creates an extra line of code, as does the index++ at the end. When you do this:
for(int i = 0; i < array.size; i++) {
doSomething(array[i]);
}
This is very concise, and your use of a for loop... if used concistently like this, immediately tells a developer that all items of this container are going to have something done with them!
Now let's use the alternate example, where we have a function that returns a boolean. And this boolean tells the loop whether to continue or not. We could do something like this:
int index = 0;
for (; doSomethingWithArrayItem(array, index); index++){
}
boolean doSomethingWithArrayItem(array, index) {
//blah blah blah
if (index + 1 == array.size) return false;
return true;
}
This accomplishes what you want, but is difficult logic to follow. Let's say that you named your doSomething function something useful, like
incrementValueByTwo(item);
What do you think this function does? It's pretty clear right. Now, let's place this function in the for loop above:
int index = 0;
for (; incrementValueByTwo(array, index); index++){
}
How many values are we incrementing? Are we incrementing all the values of the array by 2? Some of them? The first one? Or perhaps none of them under certain circumstances? THIS IS VERY CONFUSING!!!! DON'T DO THIS!
I would rather do something like
String[] array = new String[10];
for(String variable : array){
doSomething(variable);
}
Or if you are using Java 8 then
Arrays.stream(array).forEach(memberOfArray -> doSomething(memberOfArray));
This is much more readable.
As I was reading my AP java book I stumbled upon this section that made no sense to me:
...The getBalance method simply returns the current balance. A return statement obtains the value of a variable and exits the method immediately. The return value becomes the value of the method call expression. The syntax of a return statement is:
return expression;
or
return; // Exits the method without sending back a value
Why would you want to have a return statement and "exit the method without sending back a value" if you could just make it void?
***Note: Sorry if this may be too subjective. I just couldn't understand the point and the book doesn't explain it.
The return keyword doesn't need to be at the end. For example:
public static void print42(int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if (numbers[i] == 42) {
System.out.println("has 42");
return;
}
}
System.out.println("no 42");
}
It can't just use a break, as that would print both strings.
This is kind of subjective. I'm old school, I believe in one entry and exit point for all methods/functions, but...
If you have a method with a void return type and if you had reached a point in your logic which would dictate that no further processing should take place, you could call return; to force the execution to return to the calling method at this point, foregoing any further execution of the method.
It would be the same as using something like return x; in the middle of a method body that had an expected return type (of whatever x is)
It's a little like using break to break out of a loop prematurely, except you're breaking out of the method before the execution gets to the end.
There are some situations where once you've verified something inside a void function, it makes sense to exit it immediately. For example:
public static void checkIfStringInList(List<String> searchList, String findString) {
for( String thisSearchString : searchList ) {
if( findString.equals(thisSearchString) )
return;
}
throw new Exception("String " + findString + " not found in list");
}
A method declared as void can exit with a return; this is just a shortcut for early termination. A method with a non-void return type must return a value of the right type, you can not have a method return "nothing" if it has a non-void return type.
If your method has a void return type, then the return statement is optional. You might want to use it anyway if, for instance, you wanted to stop execution in certain cases.
If the return type is not void, then using return; without an argument will give you a compile error.
In java if a method has a return type in its signature, you must return an object of that type or null before exiting the method.
for example
public A foo(boolean val){
A obj=null;
if (val){
obj=new A();
obj.setSomeAttribute();
}
return obj;
}
You can not compile source code if you just code "return;"
I couldn't find anything on that while googling
so
I want to create an array only if it doesn't already exists.
EDIT: I mean not initialized
I know how to check for values in the array
Should be simple but I'm stuck
best regards
static long f(long n) {
int m = (int)n;
**if (serie == null) {
long[] serie = new long[40];
}**
if (n == 0) {
return 0;
}
else if (n==1) {
return 1;
}
else {
long asdf = f(n-1)- 2*(f(n-2)) + n;
return asdf;
}
}
something like that
a recursive function and I want to save the values in an array
You are trying to use the serie array but it is not yet declared. First declare it and then use it, as you want.
Are you looking for:
if (values == null)
{
values = new int[10];
}
or something like that? If not, please edit your question to provide more information.
EDIT: Okay, judging by the updated question, I suspect you ought to have two methods:
static long f(long n)
{
return f(n, new long[40]);
}
static long f(long n, long[] serie)
{
// Code as before, but when you recurse, pass in serie as well
}
(Note that your current code doesn't use serie at all.)
if(array==null){
//create new array
}
AFAIK, there are, if you use a variable in java, it is initialized. So you probably want to check if that variable, an array in this case, is null. Not only that, you can and probably should check if it is an array. Arrays are objects in java. So you could do something like this for an array:
if(!obj.getClass().isArray())