how to change negative number in array to their index slot - java

Im trying to change the negative numbers in the wholeNumbers array to their slot/index-number and then print out the array. Also I have to use a while loop. This is what Ive got so far, but now Im stuck. Am I on the right track copying the array? How do I proceed, is it correct that "change[counter]" be equal to "counter"? Or am my thinking wrong? When i run i get error
public class NegativeNumber {
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length) {
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
while(counter < change.length) { //get error
if(change[counter] < 0){
change[counter]=counter;
System.out.println(change[counter]);
}
}
}
}
}

public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
for(int i = 0; i < wholeNumbers.length; i++) {
if(wholeNumbers[i] < 0) {
negativeCount++;
wholeNumbers[i] = i;
}
}
}
With a while
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
int idx = 0;
while(idx < wholeNumbers.length) {
if(wholeNumbers[idx] < 0) {
negativeCount++;
wholeNumbers[idx] = idx;
}
idx++;
}
}

here is it:
import java.util.*;
public class NegativeNumber {
public static void main(String[] args)
{
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length)
{
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
counter = 0; // You forgot to reset this
while(counter < change.length)
{
if(change[counter] < 0)
{
change[counter]=counter;
System.out.println(change[counter]);
}
counter++; // You forgot to increment this
}// while
}// main
}
There were two errors, the counter variable needed to be set back to zero, and into the second while you needed to increment it again (see the comments inside the code).
The output of your program now is:
Negative numbers: 3
3
4
8

Related

task is to find the first element of an array that is not consecutive [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
Task is to find the first element of an array that is not consecutive.
E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non consecutive number.
If the whole array is consecutive then return null
Here is my solution:
import java.util.ArrayList;
import java.util.List;
class FirstNonConsecutive {
private static int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
private static List<Integer> list = new ArrayList<Integer>();
private static Integer[] arrtwovalues = new Integer[arr.length];
private static Integer solve;
static Integer find(final int[] array) {
int[] temp = new int[array.length];
int possition = array[0];
for (int i = 0; i < array.length - 1; i++) {
temp[i] = array[i + 1];
}
for (int i = 0; i < temp.length; i++) {
if (temp[i] == 0) {
temp[i] = possition;
}
}
for (int i = 0; i < array.length; i++) {
if (temp[i] - array[i] == 2) {
arrtwovalues[i] = temp[i];
}
}
for (int i = 0; i < array.length; i++) {
if (temp[i] - array[i] == 2) {
arrtwovalues[i] = temp[i];
}
}
int counter = 0;
for (int i = 0; i < arrtwovalues.length; i++) {
if (arrtwovalues[i] != null) {
counter++;
}
}
for (int i = 0; i < arrtwovalues.length; i++) {
if (arrtwovalues[i] != null) {
list.add(arrtwovalues[i]);
}
}
for (int i = 0; i < list.size(); i++) {
if (list.size() > 0) {
solve = list.get(0);
}
}
System.out.println(solve);
if (list.size() > 0) {
return solve;
}
else return null;
}
public static void main(String[] args) {
find(arr);
}
}
This is my tests:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public final class FirstNonConsecutiveTest {
#Test public void basicTests() {
assertEquals(Integer.valueOf(6), FirstNonConsecutive.find(new int[]{1, 2, 3, 4, 6, 7, 8}));
assertEquals(null, FirstNonConsecutive.find(new int[]{1, 2, 3, 4, 5, 6, 7, 8}));
assertEquals(Integer.valueOf(6), FirstNonConsecutive.find(new int[]{4, 6, 7, 8, 9, 11}));
assertEquals(Integer.valueOf(11), FirstNonConsecutive.find(new int[]{4, 5, 6, 7, 8, 9, 11}));
assertEquals(null, FirstNonConsecutive.find(new int[]{31, 32}));
assertEquals(Integer.valueOf(0), FirstNonConsecutive.find(new int[]{-3, -2, 0, 1}));
assertEquals(Integer.valueOf(-1), FirstNonConsecutive.find(new int[]{-5, -4, -3, -1}));
}
}
This test does not pass:
assertEquals(null, FirstNonConsecutive.find(new int[]{1, 2, 3, 4, 5, 6, 7, 8}));
java.lang.AssertionError:
Expected :null
Actual :6
<Click to see difference>
Process finished with exit code -1
As it says: Expected :null and Actual :6
But if I try that test-case with my main method then it returns 6 correctly and everything seems to work correctly.
Why does my test not pass? What did I miss?
Your code is way to much complicated for this task. Try something simpler to avoid mistakes, like this :
find(int[] arr) {
if(arr.length > 0) {
for(int i=1; i<arr.length; i++) {
if(arr[i]-1 != arr[i-1]){
System.out.println("The element " + arr[i] + " at the index " + i + " is the first not consecutive element of the array";
return arr[i];
}
}
}
return null; //If we reach the end of the loop, there is no number not consecutive to a previous one.
}
Currently your problem is that arrtwovalues and solve are static. So when you run your first test, you enter some values inside them. And when you run your second test, they still contain these values so it returns previous value : 6.
When you manually test your code, it return null because you did not make the first test before, so arrtwovalues and solve are not already containing values.
Because of this:
private static int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
private static List<Integer> list = new ArrayList<Integer>();
private static Integer[] arrtwovalues = new Integer[arr.length];
First of all, the variable arrtwovalues depends on the size of arr.length, which is always the same. Additionally, these values are not reset between the test runs as all of your testing code is inside the same method.
Put these variables as local variables inside your method instead and use the array.length instead:
static Integer find(final int[] array) {
List<Integer> list = new ArrayList<Integer>();
Integer[] arrtwovalues = new Integer[array.length];
int[] temp = new int[array.length];
...
This will solve that test-case, but you have one more failing test-case:
assertEquals(Integer.valueOf(0), FirstNonConsecutive.find(new int[]{-3, -2, 0, 1}));
Which seems to be caused by your code handling 0 as a special case and returning null in that case.
It would be better to put each test-case in its own method annotated by #Test, like this:
#Test
public void basicTests1() {
assertEquals(Integer.valueOf(6), FirstNonConsecutive.find(new int[]{1, 2, 3, 4, 6, 7, 8}));
}
#Test
public void basicTests2() {
assertEquals(null, FirstNonConsecutive.find(new int[]{1, 2, 3, 4, 5, 6, 7, 8}));
}
#Test
public void basicTests3() {
assertEquals(Integer.valueOf(6), FirstNonConsecutive.find(new int[]{4, 6, 7, 8, 9, 11}));
}
#Test
public void basicTests4() {
assertEquals(Integer.valueOf(11), FirstNonConsecutive.find(new int[]{4, 5, 6, 7, 8, 9, 11}));
}
#Test
public void basicTests5() {
assertEquals(null, FirstNonConsecutive.find(new int[]{31, 32}));
}
#Test
public void basicTests6() {
assertEquals(Integer.valueOf(0), FirstNonConsecutive.find(new int[]{-3, -2, 0, 1}));
}
#Test
public void basicTests7() {
assertEquals(Integer.valueOf(-1), FirstNonConsecutive.find(new int[]{-5, -4, -3, -1}));
}
You code looks complicated for this simple problem. This would do the job
public Integer findFirstNonConsecutiveNumber(int[] arr){
int element=-1;
boolean found=false;
;
for(int i=1;i < arr.length;i++){
int prev=arr[i-1];
if(arr[i]!=prev + 1)
{
element=arr[i];
found=true;
break;
}
}
if(found)
return element;
else
return null;
}
replace all field in to the method itself, and past all test.
import java.util.ArrayList;
import java.util.List;
class FirstNonConsecutive {
static Integer find(final int[] array) {
List<Integer> list = new ArrayList<Integer>();
Integer[] arrtwovalues = new Integer[array.length];
Integer solve = null;
int[] newtemp = new int[array.length];
for (int i = 0; i < array.length - 1; i++) {
newtemp[i] = array[i + 1];
}
for (int i = 0; i < array.length; i++) {
if (newtemp[i] - array[i] == 2) {
arrtwovalues[i] = newtemp[i];
}
}
for (int i = 0; i < arrtwovalues.length; i++) {
if (arrtwovalues[i] != null) {
list.add(arrtwovalues[i]);
}
}
for (int i = 0; i < list.size(); i++) {
if (list.size() > 0) {
solve = list.get(0);
}else solve = null;
}
return solve;
}
public static void main(String[] args) {
int[] arr = new int[]{4, 6, 7, 8, 9, 11};
System.out.println(find(arr));
}
}
Give it a try with the following find() method:
public Integer find(final int[] array) {
Integer val = null; // 1
for (int i = 0; i < array.length - 1; i++) { // 2
int current = array[i]; // 3
int next = array[i + 1]; // 4
if (current + 1 != next) { // 5
val = next; // 6
break; // 7
}
}
return val; // 8
}
1 - Initializing the Integer variable "val" as null.
2 - i = 0 means that the loop will start from the first element of the input "array". "i < array.length - 1" means that the loop will continue till the second last element of the array or in other words the loop will exclude the last element.
3 - Current element of the array
4 - Next element of the array
5 - Consecutive means (current + 1 = next). This if condition is checking for the not-consecutive element.
6 - If the not consecutive element is found then it is stored into the "val" variable.
7 - Since the not consecutive element is found it is not required to check the rest of the elements.
8 - If the not consecutive element is found (6) then that element will be returned, otherwise null (1) will be returned.

Finding minimum and maximum in Java 2D array

I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Arrays.sort(data);
System.out.println("Minimum = " + data[0]);
System.out.println("Maximum = " + data[data.length - 1]);
}
}
This version complies but doesn't run.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
public static int getMaxValue(int[] numbers) {
int maxValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > maxValue) {
maxValue = numbers[i];
}
return maxValue;
{
public static int getMinValue (int[] numbers) {
int minValue = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < minValue) {
minValue = numbers[i];
}
}
return minValue;
}
This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.
Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.
So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.
import java.util.*;
class MinMax {
public static void main(String[] args) {
int[][] data = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
System.out.println(getMaxValue(data));
System.out.println(getMinValue(data));
}
public static int getMaxValue(int[][] numbers) {
int maxValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] > maxValue) {
maxValue = numbers[j][i];
}
}
}
return maxValue;
}
public static int getMinValue(int[][] numbers) {
int minValue = numbers[0][0];
for (int j = 0; j < numbers.length; j++) {
for (int i = 0; i < numbers[j].length; i++) {
if (numbers[j][i] < minValue ) {
minValue = numbers[j][i];
}
}
}
return minValue ;
}
}
I have a more fun solution using Java 8 :)
IntSummaryStatistics stats = Arrays.stream(data).flatMapToInt(Arrays::stream).collect(Collectors.summarizingInt(Integer::intValue));
int max = stats.getMax();
int min = stats.getMin();
It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a Stream of ints. In order to do this first we need to call flatMapToInt. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.
Your problem is: You are sorting the array of int arrays instead of sorting each individual int in each int array.
To solve this: Loop through each int array in the array of int arrays.
Instructions for finding the maximum and minimum of a 2D int array using Arrays.sort():
Declare a 2D int array to sort called data.
Declare two ints, one to hold the maximum value, the other the minimum value.
The initial value of the maximum should be Integer.MIN_VALUE and the initial value of the minimum should be Integer.MAX_VALUE to make sure that negative values are handled.
Loop through data from 0 to data.length:
Sort data[i]
Check if the first value of data[i] is less than the minimum and change it if it is.
Check if the last value of data[i] is greater than the maximum and change it if it is.
Output your result.
Example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
for(int i = 0; i < data.length; i++) {
Arrays.sort(data[i]);
if(data[i][0] < minimum) minimum = data[i][0];
if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
}
System.out.println("Minimum = " + maximum);
System.out.println("Maximum = " + minimum);
}
}
package array;
public class Max_number {
// 2 5 7 9
// 3 6 8 1
public static void main (String[] arg) {
int a[][] = {{2,5,7,9},{3,6,8,1}};
int max=a[0][0];
for (int i=0; i<2; i++) //row
{
for (int j=0; j<4; j++) //coloum
{
if(a[i][j]>max)
{
max=a[i][j];
}
}
}
System.out.println("maximum number is"+max);
}
}

How to make a static array in main method in java?

I was reading about arrays in java and I made a code for calculating the number of appearances of all numbers in an array .
public class Example {
static int b[] = new int[13]; // I can not do static int b[] = new int[a.length] because a[] in not static array
static int count = 0;
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount();
}
private static void printCount() {
int k = 0;
for (int i = 0; i < b.length; i++) {
System.out.print("number" + " " + a[k] + " " + "is found" + " "); // here I get error in a[k] because it is not static , eclipse says : a cannot be resolved to a variable
System.out.println(b[i] + " " + "times");
k++;
}
System.out.println();
}
private static void counting(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] == a[k]) {
b[i] = ++count;
}
}
count = 0;
}
}
}
I got stuck in my printCount() method , there I can not call my a[] array in the method because a[] is not static in the main method .
I tried to write static int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 }; in my main method but eclipse does not accept that .
How can I make a[] a static array so that can be reached in all methods in my Example class above ?
Thank you
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount(a);
}
Pass the array in the printCount() method.
Why do you want a[] to be static if you don't want it moved out of the main method? The only way it can be accessed outside main() is if it was passed through. No way to call Example.a[] like a normal static variable. Seems to me like you need to get the length of a[] after it is initialized, and then set the bounds for b[] all within the main method.
You can move the a array out to the class scope as static. Then for your array practicing you can easily just change the a array.
However, as others also mention I recommend you to study scopes in Java .
public class Example {
static int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
static int[] b = new int[a.length];
static int count = 0;
public static void main(String[] args) {
counting();
printCount();
}
private static void printCount() {
int k = 0;
for (int i = 0; i < b.length; i++) {
System.out.print("number" + " " + a[k] + " " + "is found" + " ");
System.out.println(b[i] + " " + "times");
k++;
}
System.out.println();
}
private static void counting() {
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] == a[k]) {
b[i] = ++count;
}
}
count = 0;
}
}
}

returning an array of n numbers repeated into another array

Basically i have to return an array of n numbers repeated in an array into another array of length m.
my code so far:
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count = 0;
for(int j = 0; j < a.length; j++)
for(int i = 0; i < m.length; i++)
if( i == a[j]){
m[i] = count++;
}
}
return m;
} public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
Std.Out.println(i + "->" + b[i]);
} } }
this is the output im supposed to get
0->0
1->3
2->2
3->2
4->4
5->2
6->0
7->3
8->3
9->3
10->4
11->4
but im getting
0->0
1->21
2->16
3->23
4->27
5->29
6->0
7->20
8->25
9->15
10->28
11->22
what am i doing wrong?
I am not going to give you a different solution, but rather to show the mistakes in your code. If we go with the logic in your code, you have few mistakes:
1) count should be reset to 0 after first loop. Otherwise you will sum up the counts from the previous iterations.
2) count++ should be before the assignment, otherwise it will first assign and then increment. Or you could use ++count.
3) The first loop should be over i.
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count;
for(int i = 0; i < m.length; i++) {
count =0;
for(int j = 0; j < a.length; j++)
if( i == a[j]){
count++;
m[i] = count;
}
}
return m;
}
Regards.
This should solve it and do the job!
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int j = 0; j < a.length; j++) {
m[a[j]] += 1;
}
return m;
}
public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
System.out.println(i + "->" + b[i]);
}
}
}
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int i = 0; i < a.length; i++) //loop through a
if( i < M) //number check
m[a[i]]++; //add one to m at index a[i]
return m;
}
}
this is the right code for the method frequency, also checks to see if the number is in range.

Arrays-odds and evens to determine how many of the values in the array are odd and how many are even

I'm trying to find the evens and odds of an array for practice.
Sample Data :
2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61
Sample Output :
Odds - []
Evens - [2, 4, 6, 8, 10, 12, 14]
Odds - [1, 3, 5, 7, 9]
Evens - [2, 4, 6, 8]
Odds - [21, 23, 55, 61]
Evens - [2, 10, 20, 24, 40, 60]
And here is my code so far:
import java.util.Scanner;
public class OddsAndEvens
{
private static int countEm(int[] array, boolean odd)
{
int count = 0;
int dum = 0;
for(int i=0; i< array.length; i++)
{
dum = array[i] / 2;
if(dum == 0 )
{
count++;
}
}
return count;
}
public static int[] getAllEvens(int[] array)
{
int numberEvens=0;
for(int i =0; i<array.length; i++)
{
if(array[i]%2 ==0)
{
numberEvens++;
}
}
int[] evens = new int[array.length - countEm(array,false)];
int count=0;
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
public static int[] getAllOdds(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
return null;
}
}
But I been getting errors in my output. These errors are the fact I am getting zeros in my output .
I'm just starting out and I'm hoping anyone can help me.
Your main problem comes from your countEm method. It is also the reason for all the extra zeroes behind your array. By doing minimal changes can solve these problems and make your program work.
One of the major careless mistake is that you used / instead of % for checking evens and odds in your countEm method.
Your countEm method is incomplete
Using wrong operator to count even/odd
Your incomplete countEm method now only counts the number of even number no matter the Boolean value is true or false. I've helped you implemented the complete countEm:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
int numOdd = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 ) //You used / instead of % earlier!
numEven++;
else
numOdd++;
if(odd)
return numOdd;
else
return numEven;
}
Make the above changes, I am sure it will work. Of course, you haven't complete your method for getting getAllOdds yet. Above changes will make your getAllEvens work properly.
Alternatively, for myself, I like to write it this way. I prefer shorter codes:
private static int countEm(int[] array, boolean odd)
{
int numEven = 0;
for(int i=0; i< array.length; i++)
if(array[i] % 2 == 0 )
numEven++;
return odd?array.length-numEven:numEven;
}
I prevent using data structures like array list because when I see such questions, I know what are the only things you are allowed to use.
I think this would be the best way to do that:
import java.util.ArrayList;
import java.util.List;
public class EvensAndOdds {
public static List<Integer> getOdds(int[] numbers){
List<Integer> odds = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) != 0){
odds.add(numbers[i]);
}
}
return odds;
}
public static List<Integer> getEvens(int[] numbers){
List<Integer> evens = new ArrayList<>();
for(int i = 0; i < numbers.length; i++){
if((numbers[i]%2) == 0){
evens.add(numbers[i]);
}
}
return evens;
}
public static void main(String[] args){
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
List<Integer> evens = getEvens(numbers);
List<Integer> odds = getOdds(numbers);
System.out.println("Evens: ");
for(Integer even: evens){
System.out.print(even.toString() + " ");
}
System.out.println("");
System.out.println("Odds: ");
for(Integer odd: odds){
System.out.print(odd.toString() + " ");
}
}
}
What about ;):
public class EvenOddSorter {
public void sort(int[] numbers) {
Arrays.sort(numbers,new Comparator<int>() {
#Override
public int compare(int i, int y) {
if(i % 2 == 0)
return -1;
if(y % 2 == 0)
return 1;
return 0;
}
});
}
}
then extract odds and evens from your array by finding the first odd number and using
int[] evens = Arrays.copyOfRange(numbers, 0, numberOfFirstOdd);
int[] odds = Arrays.copyOfRange(numbers, numberOfFirstOdd, numbers.length)
;)
You are creating a new array with too many initial items - hence the zeros at the end. Your getAllEvens() method could look more like:
public static int[] getAllEvens(int[] array)
{
int numberEvens = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
numberEvens++;
}
}
int[] evens = new int[numberEvens]; // This has changed
int count = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] % 2 == 0)
{
evens[count] = array[i];
count++;
}
}
return evens;
}
This creates a new array with exactly the number of items you are about to populate it with.
Edit: To address your comment, here is my main() method and the output from the method above.
public static void main(String[] args)
{
int[] input =
{
2, 4, 6, 8, 10, 12, 14,
1, 2, 3, 4, 5, 6, 7, 8, 9,
2, 10, 20, 21, 23, 24, 40, 55, 60, 61
};
int[] evens = getAllEvens(input);
System.out.println(Arrays.toString(evens));
}
Which gives
[2, 4, 6, 8, 10, 12, 14, 2, 4, 6, 8, 2, 10, 20, 24, 40, 60]

Categories

Resources