I'm pretty new to Java and not from a programming background. I am doing a course and am stuck on a piece I hope this is appropriate to ask a question here). The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array. I am not including the code as I don't want the answer but I would like a clue. It's driving me nuts!
Yours in anticipation
JC
Ok, let's go through this together. Follow me:
The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array.
We have three steps here:
What I'm doing here is taking the main problem and dividing it into smaller, more approachable sub-problems. It's called divide et impera. You'll encounter this approach very often if you pursue a programming career.
main() { a[] = { "one", "two", "three"}; f(a); } f(arr[]) { for ( int i = 0 ; i < arr.length ; i++ ) print(arr[i]); }
You with me so far? I hope so.
Now,
f() would look something like:f(arr[]) { /* insert here your sorting method */ }
Once this is done, you need to pass back this array to the main function. Now, if you were to pass back a single value from a function, you would do something like:
int g() { int i = 0; i++; return i; }
since they want you to return an array, it would be something like:
int[] h() { /* initialize the array */ int[] j = { 1, 2, 3 }; /* your code goes here */ return j; }
At this point you have all elements you need for the question you were asked. Just make them work in java first, then put everything together.
Welcome to the magic world of programming :)
import org.junit.Test;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @version $Id$
*/
public class MainTest {
public SortedSet sortIntegers(Integer[] ints) {
return new TreeSet(Arrays.asList(ints));
}
@Test
public void it_should_return_a_sorted_set() throws Exception {
assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}), is(instanceOf(SortedSet.class)));
}
@Test
public void it_should_return_four_elements() throws Exception {
assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}).size(), is(4));
}
@Test
public void it_should_return_in_the_right_order() throws Exception {
Integer previous = 0;
for (Integer current : sortIntegers(new Integer[]{5, 7, 1, 6})) {
assertThat(current , is(greaterThan(previous)));
previous = current;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With