java - Input 2 integer arrays and print alternating elements - java

Conditions:
both arrays must be in order or error message
the first array must be as long as or longer than the second or error message
if the first is longer than the second it must continue to print the first
Example: given setF[] = 1,2,3,4,8 and setS[] =5,6,7 it prints 1, 5, 2, 6, 3, 7, 4, 8
The Problem With My Code: It will print and alternate fine, but will not continue to print the first areay if it's longer.
full code (I apologize for slightly messy formatting. The website screwed it up a little bit):
package mergearrays;
import java.io.*;
import java.lang.*;
import java.util.*;
public class MergeArrays {
public static void main(String[] args) {
//variables
boolean done = false;
boolean error = false;
int inpval = 0;
int i = 0; //will be setF.length
int j = 0; //will be setS.length
//arrays
int [] vals = new int[20000];
//ask user
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit");
//input array
Scanner scan = new Scanner(System.in);
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[i] = inpval;
i++;
}
else {
done = true;
}
}
done = false;
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit");
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[j+i+1] = inpval;
j++;
}
else {
done = true;
}
}
//new arrays
int [] setF = new int[10000];
int [] setS = new int[10000];
//copy vals into setF and setS
System.arraycopy(vals, 0, setF, 0, i);
System.arraycopy(vals, i+1, setS, 0, i+j+1);
//check for order
for (int p = 0; p < i - 1; p++) {
if (setF[p] > setF[p+1]) {
error = true;
break;
}
}
for (int b = 0; b < j - 1; b++) {
if (setS[b] > setS[b+1]) {
error = true;
break;
}
}
//print first array
System.out.print("\n First Array: ");
for(int q = 0; q < i; q++) {
System.out.print(setF[q] + " ");
}
//print second array
System.out.print("\n Second Array: ");
for(int m = 0; m < j; m++) {
System.out.print(setS[m] + " ");
}
//print the final set
if(i >= j && error == false){
System.out.print("\n Merged Array: ");
for(int n = 0; n <= i+j; n++) {
if(setF[n] != 0 && setS[n] !=0) {
if(n <= j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
}
else if(n > j && n <= i){
System.out.print(setF[n] + " ");
}
}
}
}
//error message
else {
System.out.print("\n ERROR: Array not in correct order");
}
}
}

the reason it didn't continue to print for you if the first array is longer lies in this line of code:
if (setF[n] != 0 && setS[n] != 0) {
You continued to print only if both of the array at the same position were zero. You should check here 'OR' not 'AND'. In addition, after changing that condition to 'OR', the ifs inside need to be changed as well, because the indexes are not correct. As follows:
System.out.print("\n Merged Array: ");
for (int n = 0; n <= i + j; n++) {
if (setF[n] != 0 || setS[n] != 0) {
if (n < j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
} else if (n < i) {
System.out.print(setF[n] + " ");
}
}
}
I would have solved it in a different way, and I can guide you to if you need some help. Anyways, Hope this helps...

Related

I am trying to make a program which will take a number and display the prime number before and after it

I am trying to make a program which will take user input as an integer and will display the prime number before it and after it. I cannot see what I have done wrong as the output is nothing. It would be great if somebody could help!
package prime;
import java.util.Scanner;
public class Prime
{
boolean flag = false;
public boolean isPrime(int x)
{
for (int i = 2; i <= x/2; i++)
{
if (x % i == 0)
{
flag = true;
return flag;
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an number. A prime number preceeding and succeeding that number will be displayed.");
int num = sc.nextInt();
Prime p = new Prime();
for (int j = num;j < num && j > 0;j--)
{
if (p.isPrime(j-1) == true)
{
System.out.println("Prime number predeceeding " + num + " : " + j);
break;
}
}
for (int j = num;j > num;j++)
{
if (p.isPrime(j+1) == false)
{
System.out.println("Prime number succeeding " + num + " : " + j);
break;
}
}
}
}
Here is a modified working code.
Made some changes:-
1.Initialized flag to true and if we find any factor just return false.
2.For finding a greater prime number just start an infinite loop from num+1. But do make sure that the input number is within the Integer value bound i.e 65535.
import java.util.Scanner;
public class Prime
{
boolean flag = true;
public boolean isPrime(int x)
{
for (int i = 2; i < x/2; i++)
{
if (x % i == 0)
{
return false;
}
}
return flag;
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an number. A prime number preceeding and succeeding that number will be displayed.");
int num = sc.nextInt();
Prime p = new Prime();
for (int j = num-1; j > 0; j--)
{
if (p.isPrime(j))
{
System.out.println("Prime number predeceeding " + num + " : " + j);
break;
}
}
for(int j=num+1; ;j++)
{
if (p.isPrime(j))
{
System.out.println("Prime number succeeding " + num + " : " + j);
break;
}
}
}
}
Hope this helps!
Your condition on both the for loops will evaluate to false. In the first case:
for (int j = num;j < num && j > 0;j--)
// for(initialization; test-condition; updation)
The test condition is false in the first iteration because you have initialized j to num and you are now checking if j < num which is false. Hence, it never goes into this loop.
Similarly, in the second case:
for (int j = num;j > num;j++)
you have initialized j to num and are now checking if j > num which is obviously false. Hence, the content of this loop is also never executed.
You can correct these by changing the initialization part in both the for loops (as suggested by #zenwraight):
for(int j = num-1; j > 0; j--) // first case
for(int j = num+1; ; j++) // second case

java unable to find the error to print a prime number

This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int inputs = 4;
input(inputs);
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
if(i != j)
System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
}
} }
public static int isPrime (int sumPair)
{
boolean primeVal =true ;
if(sumPair < 2)
primeVal= false;
else if(sumPair ==2)
primeVal=true;
else if (sumPair % 2 == 0)
primeVal = false;
else
{
int stop = (int)Math.sqrt(sumPair);
for (int d = 3; d <= stop && primeVal; d = d + 2)
{
if (sumPair % d == 0)
primeVal = false;
}
}
return(sumPair);
}
public static void input(int inputNumbers)
{
while(numbers.size() < inputNumbers){ // while there is more inputs needed
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
if(num > 0) // if the input is valid
numbers.add(num);
else // if the input is not valid
while (num <= 0) { // while the input is not valid
System.out.print("Enter a positive integer: ");
num = input.nextInt(); // get the next int if it wasn't valid
if(num > 0) { // if the input gets valid
numbers.add(num);
}
}
System.out.println("Thank you.");
}
}
public static int sumPair(int num1, int num2)
{
return num1 + num2;
}
}
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value. Try this instead:
public static boolean isPrime (int sumPair) {
boolean primeVal = true;
if (sumPair < 2 || sumPair % 2 == 0) {
primeVal = false;
}
else {
int stop = (int)Math.sqrt(sumPair);
for (int d=3; d <= stop; d += 2) {
if (sumPair % d == 0) {
primeVal = false;
break;
}
}
}
return primeVal;
}
Use this main() method:
public static void main (String args[]) {
int inputs = 4;
input(inputs);
for (int i=0; i < inputs-1; i++) {
for (int j=i+1; j < inputs; j++) {
boolean prime = isPrime(numbers.get(i) + numbers.get(j));
if (prime) {
System.out.println(numbers.get(i) + " + " + numbers.get(j));
}
}
}
}
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).
You made a nice isPrime function, you should call it.
You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.
Your code should look like:
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
ni = numbers.get(i);
nj = numbers.get(j);
if(isPrime(ni+nj)){
System.out.println(ni + " + " + nj + " = "+ (ni + nj));
}
}
}
What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.

Validate user input to only accept type int or String "quit"

My code prints out an array which is already declared then asks for user input. User is supposed to enter a number in the format xy or type quit to stop using the program. After getting user input it prints out the element of the array using x as row and y as column number which is followed by setting that index to 0 and printing the new array.
I have so far achieved most of it apart from accepting only integers or "quit" from the user. If user enters another string apart from "quit" the program crashes.
This is my code.
import java.util.Scanner;
public class Exercise23 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int [][] array = {
{0, 1, 4, 5},
{3, 7, 9, 7},
{1, 8, 2, 1}
};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
boolean exitCon = false;
do {
System.out.println("Please enter a number in the format 'xy' with no spaces in between or enter 'quit' to stop");
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <=) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
}
} while (!exitCon);
}
}
The problem is in this bit
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
I get this error "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at Exercise23.main(Exercise23.java:26)
"
Please see the code, this will cover the cases and is simple extendable:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));
String s;
while ((s=br.readLine())!=null) {
if (s.equals("quit")) {
break;
}
else if (s.matches("\\d{2}")) {
// parse it (exactly 2 digits)
System.out.print("parse:"+s);
}
else {
System.out.println("You can only enter 2dig integers or 'quit'.");
}
}
With the exception added, it appears the failure is occurring here;
String x = xy.substring(0, 1);
String y = xy.substring(1);
The StringIndexOutOfBoundsException means the String "xy" is too short, presumably blank on the readline.
The problem with your code is that any string that is not "quit" will enter the first if condition, this is what causes your code to crash. You only want to enter the fist condition if the string supplied is numeric. What your conditions should be are:
if (StringUtils.isNumeric(xy)) {
...
} else if (!xy.equals("quit")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
}
Thanks everyone. I have managed to solve my own problems with ideas from your answers and comments.
I made these changes
if (xy.length() == 2) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if ("quit".equals(xy)) {
exitCon= true;
} else {
System.out.println("You can only enter integers or 'quit'.");

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;
}
}
}
}

The values output are all correct except for the Count on the first index

import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] number = new int[50];
int index = 0;
boolean swap = true;
int temp;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = number[i];
System.out.println("\nNumbers\t" + "Occurances");
goBack: for (int i = index - 1; i >= 0; i--)
{
for (int n = index - 1; n > i; n--)
if (newNumbers[n] == newNumbers[i])
continue goBack;
int count = 0;
for (int n = 0; n < index; n++)
if (newNumbers[n] == newNumbers[i])
count++;
for(int s=0; s < newNumbers.length-1; s++){
for(int j=1; j < newNumbers.length-s; j++){
if(newNumbers[j-1] > newNumbers[j]){
temp=newNumbers[j-1];
newNumbers[j-1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println( newNumbers[i] + " " + count);
}
}
}
The code is intended to take the input through the keyboard scanner. The entered integers are compared and a list of distinct elements of the array number[] will be sorted and printed. However, The list of input contains multiples of some elements. The elements that are repeated are marked in a count. The final output should be a list of the distinct array elements (no duplicates) in order from greatest to least with their respective counts.
The input is as follows: -12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
when the sort is through and this prints, the index 4 has a count of four when it should have a count of 2. I have tried selection, bubble, and exchange sort algorithms all with similar results. Any advice would be greatly appreciated :) .
Hope this helps , though can be a better solution than this :
public static void main(String[] args) {
int[] numbers = new int[50] ;
int index = 0;
int temp;
Scanner keyboard = new Scanner(System.in);
// get the user input
System.out.print("Enter Number: ");
System.out.println(" ");
do {
int input = keyboard.nextInt();
if (input != -999)
numbers[index++] = input;
else
break;
} while (index != 0);
keyboard.close();
System.out.println("\nNumbers\t" + "Occurances");
// create a new array and store the user input
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = numbers[i];
// sort the array
for (int s = 0; s < newNumbers.length - 1; s++) {
for (int j = 1; j < newNumbers.length - s; j++) {
if (newNumbers[j - 1] < newNumbers[j]) {
temp = newNumbers[j - 1];
newNumbers[j - 1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println(Arrays.toString(newNumbers));
int count = 1;
int prevElement = 0;
if (newNumbers.length > 0) {
prevElement = newNumbers[0];
}
// print the results
for (int x = 1; x < newNumbers.length; x++) {
if (newNumbers[x] == prevElement) {
count++;
} else {
System.out.println(prevElement + " occurs " + count + "times");
prevElement = newNumbers[x];
count = 1;
}
}
System.out.println(prevElement + " occurs " + count + "times");
}
Hi If you really want shorter one ::
import java.util.*;
public class Test {
public static void main(String[] args)
{
Integer number[] = new Integer[50];
int index = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
List<Integer> asList = Arrays.asList(number);
for(Integer n: asList){
if(n != null)
System.out.println(n + " occurance " + Collections.frequency(asList,n));
}
}
}

Categories

Resources