reading Arrays output in columns - java

my main purpose is to get this kind of a output: which shows the value and the number of times it appears in a array. Below is an example, but during the code, i will ask the user for input of data integers into an array
e.g. for the array: {-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12}
The output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
below here is my own attempt, but for some reason i could not get the array to be stored, and used at other parts of the code:
import java.util.*;
public class Q4
{
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan=new Scanner(System.in);
for(int i = 0; i<myarray.length; i++)
{
int temp =scan.nextInt();
if(temp!=(-99))
{
myarray[i]=temp;
}
if(temp ==(-99))
{
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
else if(i==(myarray.length-1))
{
System.out.println("successfully filled up array fully");
System.out.println();
}
}
for(int i = 0; i<myarray.length; i++)
{
System.out.print(myarray[i]+",");
}
System.out.print("}");
int temp=0;
int number = 0;
Arrays.sort(myarray);
System.out.println("Array list: {");
for (int i = 0; i < myarray.length; i++)
{
if(temp==0)
{
temp=myarray[i];
number++;
}
else if (temp!=0)
{
if (temp==myarray[i])
{
number++;
}
else
{
temp=0;
}
}
}
System.out.print("}");
System.out.println();
System.out.println();
System.out.println("N"+"\t"+"\t"+"Count");
System.out.println(temp+"\t"+"\t"+number);
}
}
here is My output, which isnt what i wanted,
Enter integers into the system, to quit enter -99
12
3123
3123
11
22
-99
Successfully terminated by inputting -99
Array list: {12,3123,3123,11,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}Array list: {
}
N Count
3123 48

You increment number to attempt to count how many times the current array[i] has been seen, yet you never reset it's value to 0.
Also, at the end of your method, you are only printing a single row of the N Count table. If you want to print one row for each unique element of the index, don't you need to print more than one row?
There's an easier way to count the occurrences of elements in an array that doesn't require sorting it - hint, considering using a Map<Integer, Integer>.

You should try following thing.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
public class NumberRepetion {
public static void main(String[] args) {
int[] myarray = new int[50];
System.out.println("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner(System.in);
ArrayList<Integer> myarrList = new ArrayList<Integer>();
while (scan.hasNext()) {
int temp = scan.nextInt();
if (temp != (-99)) {
// myarray[i] = temp;
myarrList.add(temp);
}
if (temp == (-99)) {
System.out.println("Successfully terminated by inputting -99");
System.out.println();
break;
}
}
Hashtable<Integer, Integer> result = new Hashtable<Integer, Integer>();
System.out.print("Input Values {");
int currIndex = 0 ;
for (Integer val : myarrList) {
if (currIndex == ( myarrList.size() - 1 )){
System.out.print(val);
}else{
System.out.print(val + ", ");
}
currIndex++ ;
int currVal = val;
Integer integer = result.get(currVal);
if (integer == null || integer == 0) {
result.put(currVal, 1);
} else {
result.put(currVal, ++integer);
}
}
System.out.print("}");
System.out.println()
Enumeration<Integer> keys = result.keys();
System.out.println("N\t\tCount");
while(keys.hasMoreElements()){
System.out.println(" " + keys.nextElement() +"\t\t" + result.get(keys.nextElement()));
}
//System.out.println("\n\n\n Result " + result);
}
}
OUTPUT
Enter integers into the system, to quit enter -99
5
6
5
8
4
-99
Successfully terminated by inputting -99
Input Values {5, 6, 5, 8, 4}
N Count
8 1
5 1

What I would do is to make a new node class that has two instances, the value and count. Every time you encounter a new number, make a new node with the its value, and increment its count by one. Have a List of the nodes and add the node to this list. For the next input, have a loop check if the value has already been seen before, eg.
for i = 0; i <list.size; i++
if list.get(i).data == value // if it finds the value increment and break
list.get(i).count++
break;
else if i==list.size-1//if it went through the list and didn't find the value, make a new node of the value and add it to the list
make a new node
add it to the list
After it has terminated, sort the list by comparing list.get(i).values and swapping (bubble sort comes to mind but there are many ways to sort)
After that just print the values and it's count

If this isn't a lesson how to use Arrays, I strongly advocate in making contact with List, and other collections - but preferably List, and concretely ArrayList. It is so convenient! And it is easy.
There are 3 or 4 basic operations: Constructor to define a List, add elements, remove elements, iterate over all elements.
And about 50 other not so frequently used methods, and methods which use Lists and so on.
public static void main (String [] args)
{
List <Integer> myarray = new ArrayList <Integer> ();
System.out.println ("Enter integers into the system, to quit enter -99");
Scanner scan = new Scanner (System.in);
while (scan.hasNextInt ())
{
int temp = scan.nextInt ();
if (temp == -99)
{
System.out.println ("Successfully terminated by inputting -99");
System.out.println ();
break;
}
else {
myarray.add (temp);
if (myarray.size () == 50)
{
System.out.println ("successfully filled array fully up");
System.out.println ();
}
}
}
for (int i : myarray)
{
System.out.print (i + ",");
}
System.out.print ("}");
Set <Integer> hsi = new HashSet <Integer> ();
hsi.addAll (myarray);
Collections.sort (myarray);
System.out.println ("Array list: {");
int idx = 0;
for (int i: hsi) {
System.out.println (i + "\t" + Collections.frequency (myarray, i));
}
System.out.println (myarray.size ());
}
See how short and simple? Just add the elements - you don't need to know in advance how many elements it contains. No marker-fields or external values to mark the end necessary!
Usage:
java Numbers
Enter integers into the system, to quit enter -99
4 44 0 33 2 2 7 9 1 4 3 90 -99
Successfully terminated by inputting -99
4,44,0,33,2,2,7,9,1,4,3,90,}Array list: {
0 1
1 1
2 2
3 1
33 1
4 2
7 1
9 1
44 1
90 1
12
Your first idea for collecting values, you like to get by index or you want to iterate over, should be ArrayList, not a plain old array. Array is only useful in exceptional cases - when you surely know the size in advance to begin with.
ArrayLists are fast, believe it - no - don't believe it, test it!

Related

Index of number(s) in list in JAVA

I need to have a program that asks the user for a number, and reports that number's index in the list. If the number is not found, the program should not print anything.
Example:
Sample Output:
1
2
3
3
4
Search for? 3
3 is at index 2
3 is at index 3
This is what I have written but the put is looping multiple times. Can you suggest fixing it?
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("Search for? ");
int src = scanner.nextInt();
int ind = 0;
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = list.indexOf(src);
}
System.out.println(src + " is at index " + ind);
}
}
}
EDIT
Input: 1 2 3 3 4 -1
Search for? 3 Output: 3 is at index 0 3 is at index 0 3 is at index 2 3 is at index 2 3 is at index 2 ///So it must be only one sentence for each index. Even if I put after "for" loop, it only output the first if index.
I can see a single problem in your code, that is, you print everything, not only the matches. To solve that you need to put your System.out.println into the if, like this:
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = i;
System.out.println(src + " is at index " + ind);
}
}
Let me know if anything else was wrong.

How to find the even numbers of a list in Java [duplicate]

Code written below is correct, but I want to shorten this code.
Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.
int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {
a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 == 0) {
b[k] = a[j];
k++;
}
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 != 0) {
b[k] = a[j];
k++;
}
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {
System.out.println(b[i]);
}
Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.
Here is a simple program for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* #author Momir Sarac
*/
public class GroupByEvenAndOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a collection
List<Integer> listOfNumbers = new ArrayList<>();
// do code within a loop for 10 times
for(int i=0;i<10;i++)
{
//print to screen this text
System.out.println("Input your number:");
//get next input integer
int number = scanner.nextInt();
// add it to collection
listOfNumbers.add(number);
}
// sort this collection, list of numbers
// convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
//print sorted collection
System.out.println("Ordered list ..." + listOfNumbers);
}
}
In this version, it copies the even to the start, and the odd to the end.
static int[] sortEvenOdd(int... nums) {
int even = 0, odd = nums.length, ret[] = new int[nums.length];
for (int num : nums)
if (num % 2 == 0)
ret[even++] = num;
else
ret[--odd] = num;
return ret;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
int[] sorted = sortEvenOdd(arr);
System.out.println(Arrays.toString(sorted));
}
prints
[2, 4, 6, 10, 9, 7, 3, 1]
This Code will help you to segregate Even and Odd numbers.
// java code to segregate even odd
// numbers in an array
public class GFG {
// Function to segregate even
// odd numbers
static void arrayEvenAndOdd(
int arr[], int n)
{
int i = -1, j = 0;
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them.
Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter.
I created a simple example where I did not check for NumberFormatException when parsing the String to an int:
import java.util.Arrays;
import java.util.Scanner;
public class SortedArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of array: ");
final int arrayLength = Integer.parseInt(scanner.nextLine());
int intArray[] = new int[arrayLength];
for (int l = 0, r = arrayLength - 1; l <= r; ) {
System.out.print("Enter new array value: ");
int v = Integer.parseInt(scanner.nextLine());
intArray[v % 2 == 0 ? l++ : r--] = v;
}
System.out.println("Output: " + Arrays.toString(intArray));
}
}
Sample input/output:
Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]
I recommend reading up on streams, they will make collection processing a lot easier for you
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(0);
//this way you simply traverse the numbers twice and output the needed ones
System.out.println(numbers.stream()
.filter(x->x%2==0)
.collect(Collectors.toList()));
System.out.println(numbers.stream()
.filter(x->x%2==1)
.collect(Collectors.toList()));
//this way you can have the numbers in two collections
numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);
//this way you will have a map at the end. The boolean will tell you if the numbers are odd or even,
// and the list contains the numbers, in order of apparition in the initial list
numbers.stream().collect(Collectors.groupingBy(x->x%2==0));
A performant way to check if a number is even, is to use
if ( (x & 1) == 0 )

to display the even number followed by all odd numbers

Code written below is correct, but I want to shorten this code.
Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.
int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {
a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 == 0) {
b[k] = a[j];
k++;
}
}
for (j = 0; j < 6; j++) {
if (a[j] % 2 != 0) {
b[k] = a[j];
k++;
}
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {
System.out.println(b[i]);
}
Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.
Here is a simple program for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
* #author Momir Sarac
*/
public class GroupByEvenAndOddNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// create a collection
List<Integer> listOfNumbers = new ArrayList<>();
// do code within a loop for 10 times
for(int i=0;i<10;i++)
{
//print to screen this text
System.out.println("Input your number:");
//get next input integer
int number = scanner.nextInt();
// add it to collection
listOfNumbers.add(number);
}
// sort this collection, list of numbers
// convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
//print sorted collection
System.out.println("Ordered list ..." + listOfNumbers);
}
}
In this version, it copies the even to the start, and the odd to the end.
static int[] sortEvenOdd(int... nums) {
int even = 0, odd = nums.length, ret[] = new int[nums.length];
for (int num : nums)
if (num % 2 == 0)
ret[even++] = num;
else
ret[--odd] = num;
return ret;
}
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
int[] sorted = sortEvenOdd(arr);
System.out.println(Arrays.toString(sorted));
}
prints
[2, 4, 6, 10, 9, 7, 3, 1]
This Code will help you to segregate Even and Odd numbers.
// java code to segregate even odd
// numbers in an array
public class GFG {
// Function to segregate even
// odd numbers
static void arrayEvenAndOdd(
int arr[], int n)
{
int i = -1, j = 0;
while (j != n) {
if (arr[j] % 2 == 0)
{
i++;
// Swapping even and
// odd numbers
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
// Printing segregated array
for (int k = 0; k < n; k++)
System.out.print(arr[k] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 2, 4, 7,
6, 9, 10 };
int n = arr.length;
arrayEvenAndOdd(arr, n);
}
}
As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them.
Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter.
I created a simple example where I did not check for NumberFormatException when parsing the String to an int:
import java.util.Arrays;
import java.util.Scanner;
public class SortedArrayInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length of array: ");
final int arrayLength = Integer.parseInt(scanner.nextLine());
int intArray[] = new int[arrayLength];
for (int l = 0, r = arrayLength - 1; l <= r; ) {
System.out.print("Enter new array value: ");
int v = Integer.parseInt(scanner.nextLine());
intArray[v % 2 == 0 ? l++ : r--] = v;
}
System.out.println("Output: " + Arrays.toString(intArray));
}
}
Sample input/output:
Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]
I recommend reading up on streams, they will make collection processing a lot easier for you
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
numbers.add(7);
numbers.add(8);
numbers.add(9);
numbers.add(0);
//this way you simply traverse the numbers twice and output the needed ones
System.out.println(numbers.stream()
.filter(x->x%2==0)
.collect(Collectors.toList()));
System.out.println(numbers.stream()
.filter(x->x%2==1)
.collect(Collectors.toList()));
//this way you can have the numbers in two collections
numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);
//this way you will have a map at the end. The boolean will tell you if the numbers are odd or even,
// and the list contains the numbers, in order of apparition in the initial list
numbers.stream().collect(Collectors.groupingBy(x->x%2==0));
A performant way to check if a number is even, is to use
if ( (x & 1) == 0 )

How to print out even-numbered indexes for arrays in Java?

I'm supposed to write a program using for loops that print out the even indexes of my array. For example, if I create an array that has 10 numbers, it will have indexes from 0-9 so in that case I would print out the numbers at index 2, 4, 6 and 8. This is what I wrote so far but it doesn't work. Please note that I am not trying to print out the even numbers of the array. All I want are the even indexes.
Example I enter the following array: 3,7,5,5,5,7,7,9,9,3
Program output:
5 // (the number at index 2)
5 // (the number at index 4)
7 // (the number at index 6)
9 // (the number at index 8)
My Code:
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for (int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for (int index = 0; index < array.length; index ++)
{
if (array[number+1]%2==0)
System.out.print(array[number]);
}
}
}
You can just change your for loop and get rid of the inner IF...
for( int index = 0; index < array.length; index += 2) {
System.out.println(array[index]);
}
Just absolutely same thing using java 8 Stream API
Integer[] ints = {0,1,2,3,4,5,6,7,8,9};
IntStream.range(0, ints.length).filter(i -> i % 2 == 0).forEach(i -> System.out.println(ints[i]));
I assume this would be sufficient
// For loop to search array
for (int i = 0; i < array.length; i++) {
// If to validate that the index is divisible by 2
if (i % 2 == 0) {
System.out.print(array[i]);
}
}
This is what I did and it works:also I am not printing out index[0] because technically its not even thats why I started the for loop at 2. Your post did help me a lot. I also thank everyone else as well that took the time to post an answer.
import java.util.Scanner;
public class Arrayevenindex
{
public static void main(String[] args)
{
int number; // variable that will represent how many elements the user wants the array to have
Scanner key = new Scanner(System.in);
System.out.println(" How many elements would you like your array to have");
number = key.nextInt();
int [] array = new int [number];
// let the user enter the values of the array.
for ( int index = 0; index < number; index ++)
{
System.out.print(" Value" + (index+1) + " :");
array[index] = key.nextInt();
}
// Print out the even indexes
System.out.println("/nI am now going to print out the even indexes");
for ( int index = 2; index < array.length; index +=2)
{
System.out.print(array[index] + " ");
}
}
}

Sorting even numbers from original array

I have to create a program that reads an arbitrary number of positive integers from the user and store them into an array. The number of input data is not more than 100. After the user finishes the program should remove all even integers and place them in another array leaving all odd integers in the original array with no holes. It should display the contents in the original array as the order of input, the contents of the even integer array with a count, and the contents of the original array after taking out all even integers with a count
No third array should be used
Im having trouble displaying the original array and original integer array after taking out the even integers. here is my code so far
import java.util.*;
public class Arrays
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i=0;
int nextElm=0;
int a,b;
int[] origArray = new int[100]; /* Two arrays at length 100*/
int[] evenArray = new int[100];
while((i<origArray.length && i<evenArray.length)&& nextElm!= -1)
{
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm%2 != 0)//Sorts even numbers
{
origArray[i]= nextElm;
}
else
evenArray[i] = nextElm;
i++;
}
System.out.print("\n");
System.out.println("Even Array: ");
for (b=0; b<evenArray.length;b++)
{
if (evenArray[b]== -1)
{
evenArray[b]= 0;
}
if(evenArray[b]!= 0)
{
System.out.print(evenArray[b]+" ");
}
}
System.out.print("\n");
System.out.println("Original Array: ");
for(a=0; a<origArray.length && a<evenArray.length; a++)
{
if (origArray[a]== -1)
{
origArray[a]= 0;
}
if(origArray[a]!= 0)
{
System.out.print(origArray[a]+" " + evenArray[a]);
}
}
System.out.print("\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i = 0;
int nextElm = 0;
int a, b;
int[] origArray = new int[100]; /* Two arrays at length 100 */
int[] evenArray = new int[100];
while (nextElm != -1) {
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm > 0) {
origArray[i] = nextElm;
i++;
}
}
int x = 0;
System.out.println();
// Displays original array and sorts even numbers to even array +
// original count
System.out.printf("\nTotal count of original array is : %d", i);
System.out.println();
for (int orgNumber : origArray) {
if (orgNumber != 0) {
System.out.print(orgNumber + " ");
}
if (orgNumber % 2 == 0) {
if (orgNumber != 0) {
evenArray[x] = orgNumber;
x++;
}
}
}
System.out.println();
// Displays sort even numbers to even array + even count
System.out.printf("\nTotal count of even array is : %d", x);
System.out.println();
for (int evenNumber : evenArray) {
if (evenNumber != 0) {
System.out.print(evenNumber + " ");
}
}
// Displays sort odd numbers from original array + odd count
System.out.printf("\nTotal count of orignal array without even is : %d", i - x);
System.out.println();
for (int oddNumber : origArray) {
if (oddNumber % 2 != 0) {
System.out.print(oddNumber + " ");
}
}
}
This should work perfectly if I understood your question well. Hope you find this helpful.
You want three separate loops. One for inputting the values (I would suggest the while construct as you have done) and one for sorting the values.
Your input loop should read in a new number each time and only quit when the user wants to. For example, if the user inputs a negative number, then your loop will quit. Like this:
System.out.println("Enter any number of numbers; enter a negative when finished.");
int nextElm = 0;
int count = 0;
while (nextElm >= 0) {
nextElm = scan.nextInt();
origArray[count] = nextElm;
count++;
}
// This is where you would put a print statement that prints the original array with a count.
Now after this, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array, like so:
origArray = java.util.Arrays.copyOf(origArray, count+1);
Next, use a for loop to iterate through the array, and move even numbers to the other array. This is the tricky part, because removing items from an array requires iteration to move each value to it's previous index.
int j = 0;
for (int i=0; i<count; i++){
if (origArray[i] % 2 == 0){
evenArray[j] = origArray[i]; //add even number to evenArray
j++; //move to next index of evenArray
for (int k=i; k<(origArray.length-1); k++){
origArray[k] = origArray[k+1]; //store next value in current index
}
}
}
Then finally, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array again, like so:
evenArray = java.util.Arrays.copyOf(evenArray, j+1);
Disclaimer: This was all coded from the hip so let me know if I missed something or did something incorrectly.

Categories