Trying to print the frequency of integers in an array - java

I'm trying to print out the frequency of each integer in an array
import java.util.*;
public class NumFrequency {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers your going to input, up to 50");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the "+ num + " numbers now.");
for (int i=0 ; i<array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("array created");
printArray(array);
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; i++) {
System.out.print(arr[i]+" ");
}
}
private static int[] intFreqArray = new int[51];
public static void FreqOfInt(int[] array, int num) {
for (int eachInt : array) {
intFreqArray[eachInt]++;
}
for (int m = 0; m<intFreqArray.length; m++) {
if (intFreqArray[m] > 1) {
System.out.println(m+ " occurs " + intFreqArray[m] + " times.");
}
}
}
}
It'll print out the array created by the user but nothing after that I'm lost as to why it wont print out the last part.

You need to call FreqOfInt before you print.
Note that we normally use lower case letters for the names of Java methods.

In main, the last method call is to printArray, but you never call FreqOfInt. That's why that output doesn't show up.
Call it after calling printArray.

Related

How to determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Java for-loop is not executed

The first for-loop you see does not execute and I'm not sure why. It is completely ignored, I tried it in a separate method and I tried it in the main method but something seems to be ignoring but I'm not sure how to get it to run, it simply goes to the next method run in the main method.
package math;
import java.util.Scanner;
public class mathAverageValue {
static int numOfVals;
static double total;
static double average;
static double[] arr = new double[numOfVals];
static String boole;
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
public static void process() {
for (int i=0; i < arr.length; i++) {
total = total + arr[i];
}
average = total / arr.length;
}
public static void output() {
System.out.println("Your average is : " + average);
System.out.println("Would you like to average again? Y or N : ");
Scanner i = new Scanner(System.in);
boole = i.next();
if ("Y".equals(boole)) {
input();
output();
}
}
public static void main(String[] args) {
input();
output();
}
}
Assign some value to static int numOfVals. Java by default assign 0 to it. Hence your for loop will never run. Also modify your array declaration like below:-
static double arr = new double[numOfVals];
The problem is that you have assigned a value to numOfVals and then created the array in the wrong order.
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
arr = new double[numOfVals]; // <-- PUT THIS HERE
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
It is ignored because it is a zero length array:
static int numOfVals; // This implicitly equals 0.
static double total;
static double average;
static double[] arr = new double[numOfVals]; // so this has no elements.
hence
for(int i=0; i<arr.length; i++){ //arr.length is 0
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
doesn't iterate
According to java primitive data types initialization, all types have a default value. In your case, static int numOfVals will be assigned with 0. This is the reason why the for loop is ignored. see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

Java. Program crashes when entering any odd number with even numbers

The program is meant to count how many even numbers that have been inputted by the user. However, when the user inputs even numbers along with odd numbers the program crashes. But when the user enters all odd or even the program works fine. I can't seem to find the error either as the error message returns:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at AllEven.getEven(AllEven.java:52)
at AllEven.read(AllEven.java:41)
at AllEven.main(AllEven.java:10)
Java Result: 1
The code for the program is below and any help would be greatly appreciated
import java.util.Scanner;
public class AllEven
{
private static int evenCount;
private static int[] evenArray;
private static int count;
public static void main (String args [])
{
read();//LINE 10
}
public static int [] read ()
{
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the array");
int arrayIn = scanner.nextInt();
if (arrayIn == 0)
{
System.out.println("No Array");
}
else
{
System.out.println("------------------");
}
int userArray [] = new int [arrayIn];
for (int i = 0; i < userArray.length; i++)
{
System.out.println("Please enter a value for position: " + i);
arrayIn = scanner.nextInt();
userArray[i] = arrayIn;
if (arrayIn % 2 == 0)
{
evenCount++;
}
}
getEven(userArray);//LINE 41
return userArray;
}
public static int [] getEven(int[] userArray)
{
if (evenCount > 0)
{
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i]; //LINE 52
count++;
}
print (evenArray);
}
else
{
System.out.println("No even numbers found");
}
return evenArray;
}
public static void print (int [] evenArray)
{
System.out.println();
System.out.println("Even numbers in the array are: ");
for (int i = 0; i < evenArray.length; i++)
{
System.out.println(evenArray[i]);
}
}
}//endprogram
userArray.length is not always equal to evenCount
problematic code
evenArray = new int [evenCount];
for (int i = 0; i < userArray.length; i++)
{
evenArray[count] = userArray[i];
Your even count is less than the size of the user array, yet you are indexing into the even array count times. You are incrementing count each time you get an item from the input array, and the input array will always be larger than the even array if you enter both even and odd numbers.

Program has error lines which are remarked by ???? .I could not understand where the problem is

public static void main (String args[]) {
Scanner myinput=new Scanner(System.in) ; //Arrary length comes from user!
System.out.println("Enter a number: ") ;
int sayi=myinput.nextInt() ;
int [] Array = new int [sayi] ;
for(int i=0; i<SayiDizisi.length ; i++){ //Fill the array!(Comes from user)
System.out.println("Enter the numbers: ") ;
SayiDizisi[i]=myinput.nextInt() ;}
}
Max(int [] SayiDizisi) ; // ???????????????????????????????????
}
public static int Max(int [] Array1) {
int max=SayiDizisi1[0] ;
for(int i=0; i<SayiDizisi1.length ; i++) {
if(SayiDizisi1[i]>max)
max=SayiDizisi1[i] ;
}
return SayiDizisi ; //?????????????????????
}
}
For a start, you should not have the int [] type in the method call. Change:
Max (int[] SayiDizisi);
to:
Max (SayiDizisi);
Secondly, your Max function is expected to return an integer but it's returning an array of integers. Change its return statement from:
return SayiDizisi;
to:
return max;
Thirdly, I can't see where SayiDizisi is defined anywhere. You appear to be creating an array to be populated but you've called it Array. Change:
int[] Array = new int[sayi];
to:
int[] SayiDizisi = new int[sayi];
Finally, your braces are not balanced. See the line SayiDizisi[i]=myinput.nextInt() ;} - it has a superfluous brace at the end which causes the compiler to misunderstand your intent.
Here's a fully functioning one with those fixes made, and some comments added for your education:
import java.util.Scanner;
public class scratch {
public static void main (String args[]) {
// Get the count and allocate array.
Scanner myinput = new Scanner (System.in);
System.out.println ("Enter a number: ");
int sayi = myinput.nextInt();
int[] SayiDizisi = new int[sayi];
// Get the values into the array.
for (int i = 0; i < SayiDizisi.length ; i++) {
System.out.println ("Enter the numbers: ");
SayiDizisi[i] = myinput.nextInt();
}
// Output the maximum.
int x = Max (SayiDizisi);
System.out.println ("Maximum is: " + x);
}
public static int Max(int[] Array1) {
// Assume first is largest.
int max = Array1[0] ;
// Check all others, finding larger.
for (int i = 0; i < Array1.length ; i++) {
if (Array1[i] > max)
max = Array1[i];
}
// Return the largest found.
return max;
}
}

Categories