Java: How to get address of array? [closed] - java

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 6 years ago.
Improve this question
I am trying to convert a C++ code to Java.
The C++ code snippet is: findMedian(array+left+i*5, 5);.
The parameter passed is the array address which changes according to the value of i. How can I modify this code so that it works in Java?The method is as below:
public int findMedian(int arr[], int n)
{
Arrays.sort(arr);
return arr[n/2]; // Return middle element
}

You can use the other overload of Arrays.sort to sort only part of the array:
public static int findMedian(int arr[], int from, int n) {
Arrays.sort(arr, from, from + n);
return arr[from + (n / 2)]; // Return middle element
}
Then call like:
findMedian(array, left + i * 5, 5);

As others have said, Java doesn't let you perform math on pointers, or really look at them at all. In general, in Java, pointers and memory are the compiler's problem, not yours.
That being said, you should still be able to look over the values in an array; just pass it a reference to the array itself, and then do whatever computations are necessary on the indices. Tough to get more specific without knowing exactly what that method does.

In java is not possible to address directly memory locations.
In C memory is addressed with a pointer.
In java memory is addressed with a reference.
For a comparison between java and C see this link from Princeton University.

Is this workable?
findMedian(array, left+i*5, 5);
Signature:
public int findMedian(int[] array, int offset, int value1) {
//...
}

Related

Recursions in Java [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 10 days ago.
This post was edited and submitted for review 10 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm starting with recursion in Java, and I'm having a problem with a counter, where I want to print all numbers from 1 to number, but it only prints the value of i. i was defined at the start of the class as:
int i = 1;
I've tried putting
i>=number
number>=i
i>=1
number>=0
number>=1
number>0
number>1
After getting rid of i, I also tried:
public static void ContadorCreciente(int number) {
if (i <= number) {
System.out.println(i);
ContadorCreciente(i++);
}
}
But now, this is what I've written so far:
public static void ContadorCreciente(int number) {
if (number > 1) {
ContadorDecreciente(number - 1);
System.out.println(number);
}
}
Ok, you're implementing ContadorCreciente with one number argument. Recursive, so you're going to call it again with either number+1 or number-1. For the +1 variant you have no way to stop it, that would keep going up forever, so that's no good, the recursive call has to be with -1.
The -1 recursion can stop e.g. at ContadorCreciente(0) which is expected to do nothing. I'm sure you can figure out how to do nothing and return immediately.
Inductive approach:
Assuming we already have ContadorCreciente(number-1) which prints all numbers 1..number-1. How would you use such a function to implement the case ContadorCreciente(number)?

What is the best practice for a Stream of one element? [closed]

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 3 years ago.
Improve this question
Suppose I have a method
void doSomething(int x){
Stream<Long> stream = someUtil.getSomething(x);
}
Suppose I have a utility function someUtil.getSomeStream(x), which returns a stream of at most size 1.
class SomeUtil {
/* Returns Stream<Long>, the stream can have size at most 1 */
public static Stream<Long> getSomething(x){
Optional<Long> opt = doSomethingWithXAndReturnOptional(x);
return opt.map(Stream::of).orElse(Stream.empty());
}
}
The debate I am having is whether to make this method return a Stream<Long> which will have at most size 1 versus return an Optional<Long>, which the callers will convert like this:
void doSomething(int x){
Stream<Long> stream = Stream.of(someUtil.getSomething(x).get()); //convert to stream ourselves as the caller
}
We only have one caller for now doSomething(int x) but it would be easier for this caller (and most likely future callers) to expect a Stream. At the same time it could be misleading that we are returning a Stream of size 1 always.
What is the correct, readable, maintainable and least confusing approach here?
This is not an adequate question as it opens a debate.
If you method contract is to return at most 1 value, returning an Optional is much more readable imo.
If you method contract is to stream values, return a Stream is much more readable.
You can use Optional::stream and Stream::findFirst to convert between the two as required.(java 9 https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#stream--).

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.

Can somebody please tell me how to translate this equation into a Java process? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know how to translate this:
into a Java process that looks like:
public static float computeAverage(float [] i){
//I have no idea what this is supposed to be.
}
or perhaps even
public static double computeAverage(double [] i){
//Still have no idea what this is meant to be.
}
If it's easier to answer with doubles, that's fine, but I really don't need that level of precision.
*Edit:*Okay, tell me if this looks right:
public static float computeAverage(float [] i){
float tally = 0f;
for(int x=0;x<i.length;x++){
tally = tally + pValue(i[x]);
}
return tally / i.length;
}
public static float pValue(float i){
return 2 - 1f/i;
}
I don't want to do your work right away, because it won't help you in the future. But I'll try to give you hints.
Java elements
The different elements that you might need are the following:
the number n, which is the number of elements in your input array, can be accessed using myInput.length
to iterate with a moving k index, you'll need a for loop. Check this out to know how to use for loops.
you'll have to be careful that in Java, arrays are indexed starting at 0, not 1. So to access Ck, you'll actually write myInput[k-1].
Break down your problem
What do you want to achieve? You're not just "translating this formula into Java code", but you're writing a method (a function) which, given an input array of Ci, returns an average following the specified formula.
I think your assignment is to write the following function:
Maybe you should try to:
write a little method for p()
write a for loop that performs a sum (the internet is full of these)
adapt your for loop using p()
divide the result of the for loop by n
return the divided result
UPDATE: it's much easier to help you once you've tried something :)
Your code looks fine overall now. According to your formula I think you're adding the wrong value to the sum in your loop).
It should probably be: tally = tally + pValue(i[x])

How to check an array before populating it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone know how can I populate an array that checks if the positions are filled before filling them, and if they are already filled and if that array position is filled it increments to the next one.
Thanks
Primitive array elements are never empty. For example in an int array all elements will be initialized to 0.
So if you want to check for filled or not, initialize the array elements to a value which it is not going to take. say -1. Then each time you make an entry check for -1. The dummy value initialization is necessary as you can not check for 0, because 0 can be a valid data as well
// Initialization part
int [] arr= new int [17];
for(int i=0;i<arr.length;i++)
{
arr[i]= -1;
}
Hope you will do the checking part yourself
I am assuming (possibly incorrectly) that you either a) want a method that inserts object into the first available (i.e. not null) spot in the array at or past the argument integer or b) want to insert repeatedly into the array using the method in a)
the method in a) would basically be as follows
public <Type> void myInsertMethod(Type[] array,Type item,int position)
{
while (array[pos]!=null)
{pos++;}
array[pos]=item;
}
if you want to do this repeatedly on the same array, just call the method repeatedly, with different positions and items.
You can check if the position you are going to fill it's not null, or empty, or at least the stored value it's different to the one you are going to put
if(array.get(index) != "" && array.get(index) != null) && array.get(index) != newObject){
array.add(newObject);
}
Then, depending on the stored value type, you can ddo some more checks, for example in the cas e of the int, as RookieB says, you can check if the object is different to 0
Hope it helps

Categories

Resources