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.
Related
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
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] + " ");
}
}
}
So I've been tasked with creating a code that creates a predetermined array list for users to input up to over 100 integers with the option of using 0 to signify once their done with their inputs. However, when trying to call for say the minimum value, it just returns a value of 0. How would I properly format it so it compares it to all the value in the user inputted array list? Appreciate any help I can get! I added comments on the side to show which areas I have questions about or where I believe that the error lies.
public static void main(String[] args) {
Scanner TextIO = new Scanner(System.in);
String calc;
double[] numbers2; //An array for storing double values.
int[] numbers; // An array for storing the int values.
int count; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.
int max;
int min;
/* Initialize the summation and counting variables. */
numbers2 = new double[100]; // Space for 100 doubles.
numbers = new int[100]; // Space for 100 ints.
count = 0; // No numbers have been saved
max = Integer.MIN_VALUE; //Properly initialized?
min = Integer.MAX_VALUE; //Properly initialized?
/*Start of min method. */
if (calc.equals("min")){
System.out.println("Enter up to 100 positive integers;
while (true) { // Get the numbers and put them in the array.
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break; } /*Zero marks the end of the input. All
have been inputted. */
else {
numbers[count] = num; // Put num in position count.
count++;
}
for (int i=0; i<numbers.length;i++) { //"For" statement needed here?
if (numbers[i] < min) {
min = numbers[i];}
}
}
System.out.println("Your minimum is : " + min);
}
}
}
Your for loop that finds the minimum should be after the while loop that reads the input, not inside it (since currently it goes over un-initialized elements of the array, so it always finds a 0 as the minimum). If you do that, you should also change the for loop to only iterate over the elements you assigned to the array (indices 0 to count-1), and not the entire array.
Alternately, you can remove the for loop and just put the
if (numbers[count-1] < min) {
min = numbers[count-1];
}
condition inside the while loop.
This will find the minimum in the same loop that reads the input.
Of course, if you do that, you don't need to store the elements in an array at all, so you can further simplify the code.
Here's a possible solution the keeps the array and the for loop :
while (count < numbers.length) { // avoid too many inputs
System.out.print("-> ");
num = TextIO.nextInt();
if (num <= 0) {
break;
} else {
numbers[count] = num;
count++;
}
}
for (int i=0; i<count;i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
First post here so I'm hoping I don't screw up.
My task is to have a user enter an array of 10 integers and then input another integer separately and have the program either retrieve that number if it's in the array, or give an error if not.
I'm having trouble comparing the inputted integer with those in the array.
Here's part of my code, with the rest found below:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
http://pastebin.com/U5PdJgr6
Thank you in advance!
If you're using java-8, you can perform that easily using an IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);
Turn
if (numbers[index] == compare) {
System.out.print(compare);
}
Into
boolean found;
for (int number : numbers) {
found = number == compare;
if (found) break;
}
if (found) System.out.print(compare);
else throw new Exception("Number Not Found");
P.S. You don't need to check to make sure numbers.length is still 10. The length of an array is always final and can't change.
package integerarrayexceptions;
import java.util.Scanner;
import java.util.InputMismatchException;
public class IntegerArrayExceptions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[] = new int[10];
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt(); //The loop only applies to this statement.
if(numbers.length==10){
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
for (int index2 = 0; index2 < numbers.length; index2++) {
if(numbers[index2] == compare){
System.out.print(compare);
}
}
}
}
catch (InputMismatchException MismatchException)
{
System.out.print("One or more values entered is not an integer.");
}
}
}
There's a loop missing after you entered the compare value:
for (index = 0; index < numbers.length; index++) {
if(numbers[index] == compare){
System.out.print(compare);
}
]
You try to use the variable "index" outside the "for" loop, where it does not exist...
I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number.
How should I assign the array length?
If user enters 5 6 7 8 9 (5 numbers), then
int[] list;
becomes
int[] list = new int[5];
I'm trying to use a loop, but it won't stop.
int[] integers;
int j = 0;
do {
integers = new int[j + 1];
integers[j] = in.nextInt();
j++;
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.
import java.util.Scanner;
public class ArrayModify {
public static void main(String[] args) {
int[] list;
String st;
String[] stNew;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9
st = scan.nextLine();
stNew = st.split("\\s+");
list = new int[stNew.length]; // Sets array size to 5
for (int i = 0; i < stNew.length; i++){
list[i] = Integer.parseInt(stNew[i]);
System.out.println("You Enterred: " + list[i]);
}
}
}
String line=sc.nextLine();
int counter=1;
for(int i=0;i<line.length();i++) {
if(line.charAt(i)==' ') {
counter++;
}
}
long[] numbers=new long[counter];
counter=0;
for(int i=0;i<line.length();i++){
int j=i;
while(true) {
if(j>=line.length() || line.charAt(j)==' ') {
break;
}
j++;
}
numbers[counter]=Integer.parseInt(line.substring(i,j));
i=j;
counter++;
}
for(int i=0;i<counter;i++) {
System.out.println(numbers[i]);
}
I always use this code for situations like this. beside you can recognize two or three or more digit numbers.
int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
arr[j] = scan.nextInt();
}
The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.
**input of list of number for array from single line.
String input = sc.nextLine();
String arr[] = input.split(" ");
int new_arr[] = new int[arr.length];
for(int i=0; i<arr.length; i++)
{
new_arr[i] = Integer.parseInt(arr[i]);
}