Separating the 0s and Positive Numbers in two different arrays - java

This is the code I have written, My objective is to segregate the 0s and non 0s without changing the order of the non 0s
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i = 0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[i] = q;
} else if (q == 0) {
ary[i] = q;
}
}
for (int j = 0; j < arx.length; j++) {
System.out.print(arx[j] + " ");
}
for (int j = 0; j < ary.length; j++) {
System.out.print(ary[j] + " ");
}
}
}
Sample i/p:
5
0 1 0 3 12
Sample o/p:
1 3 12 0 0
What I am getting:
o/p:
0 1 0 3 12 0 0 0 0 0

You should maintain separate index counters for the two arrays:
int x = sc.nextInt();
int ix = 0;
int iy = 0;
int[] arx;
arx = new int[x];
int[] ary;
ary = new int[x];
for (int i=0; i < x; i++) {
int q = sc.nextInt();
if (q != 0) {
arx[ix++] = q;
}
else if (q == 0) {
ary[iy++] = q;
}
}
for (int i=0; i < ix; i++) {
System.out.print(arx[i] + " ");
}
for (int i=0; i < iy; i++) {
System.out.print(ary[i] + " ");
}
For your inputs the above generated the following output:
1 3 12 0 0

Since array with arx is filled with zeroes , you can only use one array to add non zero values.
{
Scanner sc = new Scanner (System.in);
int x = sc.nextInt ();
int[] arx;
arx = new int[x];
int ind = 0;
for (int i = 0; i < x; i++) {
int q = sc.nextInt ();
if (q != 0){
arx[ind++] = q;
}
}
for (int j = 0; j < arx.length; j++){
System.out.print (arx[j] + " ");
}
}

Related

Array program not running correctly. How do I fix it?

Trying to write a program that asks the a user for 10 integers as input. The program
places the even integers into an array called evenList, the odd integers into
an array called oddList, and the negative numbers into an array called
negativeList. The program displays the contents of the three arrays after
all of the integers have been entered.
This is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int countNeg = 0;
int countOdd = 0;
int countEven = 0;
int[] list = new int[10];
System.out.println("Please enter 10 integers:");
for(int i = 0; i < list.length; i++)
{
list[i] = scan.nextInt();
if(list[i] < 0)
{
countNeg++;
}
if(list[i] % 2 == 0 && list[i] > 0)
{
countEven++;
}
if(list[i] % 2 == 1 && list[i] > 0)
{
countOdd++;
}
}
int[] oddList = new int[countOdd];
int[] evenList = new int[countEven];
int[] negativeList = new int[countNeg];
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
for(int j = 0; j < countNeg; j++)
{
negativeList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
for(int j = 0; j < countEven; j++)
{
evenList[j] = list[i];
}
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
for(int j = 0; j < countOdd; j++)
{
oddList[j] = list[i];
}
}
}
for (int i : negativeList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList)
{
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList)
{
System.out.print(i + " ");
}
}
}
The program prints the Arrays with the correct amount of values but the wrong numbers. It prints only the last negative, even, or odd number to be input. ex input is 1, 2, 3, 4, 5, 6, -1, -2, -3, -4. For negativeList it prints -4 -4 -4 -4. Im guessing something is wrong in the loops after the arrays are created. Please help!!
you can very much simplify your code with using ArrayList instead of array. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = 10;
System.out.println("Please enter 10 integers:");
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
List<Integer> negativeList = new ArrayList<>();
for (int i = 0; i < length; i++) {
int n = scan.nextInt();
if (n < 0) {
negativeList.add(n);
} else if (n % 2 == 0) {
evenList.add(n);
} else {
oddList.add(n);
}
}
for (int i : negativeList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : evenList) {
System.out.print(i + " ");
}
System.out.println();
for (int i : oddList) {
System.out.print(i + " ");
}
}
there are a few issues with the code you provided.
First, in the for loops that initialize the negativeList, evenList, and oddList arrays, you are overwriting the values at each iteration. This means that the final arrays will only contain the last value that was assigned to them. To fix this, you can use a counter variable to keep track of the next index to be filled in each array, like this:
int negCounter = 0;
int evenCounter = 0;
int oddCounter = 0;
for(int i = 0; i < list.length; i++)
{
if(list[i] < 0)
{
negativeList[negCounter] = list[i];
negCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 0 && list[i] > 0)
{
evenList[evenCounter] = list[i];
evenCounter++;
}
}
for(int i = 0; i < list.length; i++)
{
if(list[i] % 2 == 1 && list[i] > 0)
{
oddList[oddCounter] = list[i];
oddCounter++;
}
}
Second, you are not checking if the input values are integers. If the user enters a non-integer value, the program will throw an exception. You can add a check to make sure that the input is an integer like this:
if(scan.hasNextInt())
{
list[i] = scan.nextInt();
// ... rest of the code
}
else
{
System.out.println("Please enter an integer.");
// If the input is not an integer, discard it and move to the next
input
scan.next();
}

How to get sum of array elements between two zeros

first input: size of array: 5
second input: 0 -2 4 0 6
output: 2
Here is what I have tried. It is also adding the numbers before zero:
My code's output:
array size: 10
elements: 6 19 0 -3 4 8 0 -6 9 59
my output: 25 9
import java.util.Scanner;
import java.util.Vector;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
Vector<Integer> A = new Vector<Integer>();
int sum = 0;
for(int i=0; i<arr.length; i++){
arr[i] = in.nextInt();
}
for(int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
i++;
break;
}
}
for(int i=0; i < arr.length; i++)
{
if (arr[i] == 0)
{
A.add(sum);
sum = 0;
}
else
{
sum += arr[i];
}
}
for(int j = 0; j < A.size(); j++)
{
System.out.print(A.get(j) + " ");
}
}
}
You don't need 2 loops, one to look for the first zero and then sum up.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
List<Integer> sums = new ArrayList<>();
int sum = 0;
// read input
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
boolean isCounting = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0 && isCounting) {
sum += arr[i];
} else if(arr[i] == 0){
// if already counting then finish the sum
if (isCounting) {
sums.add(sum);
sum = 0;
} else { // else start counting
isCounting = true;
}
}
}
System.out.println(sums);
}
}
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int arr[] = new int[size];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
int sum = 0;
int idx = 0;
while (arr[idx] != 0)
idx++; // After this, idx will be the index of the first 0
do {
idx++; // Keep looping from idx + 1 until the next 0
if (arr[idx] != 0 && idx < arr.length)
sum += arr[idx];
} while (idx < arr.length && arr[idx] != 0);
System.out.println("Sum = " + sum);
}
}
int sum = -1;
int j = -1;
for(int i=0; i<arr.length;i++ ){
if (arr[i] == 0) {
j = i;
if (sum == -1)
sum = 0;
else
break;
}
if ( j == -1)
continue;
sum += arr[i];
}
The above should work
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
int sum = 0;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
if (arr[i] == 0) {
list.add(i);
}
}
for (int i = list.get(0); i <= list.get(list.size()-1); i++) {
sum += arr[i];
}
System.out.println(sum);
}

How do i put the total sum of prime numbers first, then the prime numbers below it

I'm currently using this code, and I'm trying to output the total sum of how many prime numbers first and then the prime numbers list
Here is my code:
import java.util.*;
public class PrimeTime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
System.out.print(i+ " ");
s = s +1;
}
}
System.out.println("N =" +s);
}
}
This is the result I get:
Input number: 10
2 3 5 7 N = 4
But what I'm looking for is this result:
Input number: 10
N = 4
2 3 5 7
I don't know how, I tried putting the S.O.P in different places and I can't figure out how.
If you want to display N = 4 before 2 3 5 7, you can append the numbers (i.e. 2 3 5 7) to a StringBuilder and print the same after printing N = 4 e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
StringBuilder numbers = new StringBuilder();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0)
f = 1;
}
if (f == 0) {
numbers.append(i).append(' ');// Append to StringBuilder instead of printing
s = s + 1;
}
}
System.out.println("N =" + s);
System.out.println(numbers);
}
}
A sample run:
Input number: 10
N =4
2 3 5 7
Note: for checking the primality, checking up to Math.sqrt(i) is sufficient i.e. you should replace j < i with j <= Math.sqrt(i).
You can store the numbers in a list and then print them after the loop is over
Don't worry if you have not studied lists yet cause you will have to soon anyways.
here's the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
LinkedList<Integer> list = new LinkedList<>();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
//System.out.print(i+ " ");
list.add(i);
s = s +1;
}
}
System.out.println("N = " +s);
for(int i = 0; i<list.size(); i++ ) {
System.out.print(list.get(i) + " ");
}
}

JAVA program bug when populating array from different array

When population oddList, evenList and negativeList from the inputList the program only populates it with one int instead of all corresponding ints from the inputList array. The output should be a list from each array whose numbers correspond to its title. The numbers are input by user into inputList array and then from there it determines whether it is odd, even, and negative and then fills the corresponding arrays.
I.E. evenList is filled with even ints from inputList.
public class ProjectTenOne
{
public static void main(String[] args)
{
int[] inputList = new int[10];
int[] oddList = null;
int[] evenList = null;
int[] negativeList = null;
int evenCount = 0;
int oddCount = 0;
int negCount = 0;
Scanner input = new Scanner(System.in);
//System.out.println("Enter any ten integers: ");
for(int list = 0; list < inputList.length; list++)
{
System.out.println("Enter any " + (inputList.length - list) + " integers: ");
inputList[list] = input.nextInt();
}
System.out.println();
System.out.println("The numbers you entered: ");
for(int in = 0; in < inputList.length; in++)
{
System.out.println(inputList[in]);
}
for(int ls = 0; ls< inputList.length; ls++)
{
if(inputList[ls] % 2 == 0)
{
evenCount = evenCount +1;
}
if(inputList[ls] % 2 != 0)
{
oddCount = oddCount +1;
}
if(inputList[ls] < 0)
{
negCount = negCount +1;
}
}
evenList = new int[evenCount];
oddList = new int[oddCount];
negativeList = new int[negCount];
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
for(int j = 0; j < evenList.length; j++)
{
evenList[j] = inputList[l];
}
}
if((inputList[l] % 2) != 0)
{
for(int k = 0; k < oddList.length; k++)
{
oddList[k] = inputList[l];
}
}
if(inputList[l] < 0)
{
for(int h = 0; h < negativeList.length; h++)
{
negativeList[h] = inputList[l];
}
}
}
System.out.println("The ODD List is: ");
for(int i = 0; i < oddList.length; i++)
{
System.out.println(oddList[i]);
}
System.out.println("The EVEN List is: ");
for(int j = 0; j < evenList.length; j++)
{
System.out.println(evenList[j]);
}
System.out.println("The NEGATIVE List is: ");
for(int k = 0; k < oddList.length; k++)
{
System.out.println(negativeList[k]);
}
}
}
I'll take evenList as the example here, but the same applies to the other two arrays as well.
In your code, you iterate over your inputList and check for an even number. If it is even, you set the entire evenList array to the found value, instead of just a single element.
You can solve this problem by declaring an int outside of your outer loop that keeps track of the number of even numbers entered. As an example:
int evenIndex = 0;
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
evenList[evenIndex++] = inputList[l];
}
/*Other code*/
}
You also made a mistake in your last loop. You iterate over negativeList, but you use the size of evenList. This will result in an ArrayIndexOutOfBoundsException when negativeList is smaller than evenList.

Problems Sorting a two column array and outputting value frequency in Java

Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
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
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}

Categories

Resources