Largest Occurrence Count - java

Im new to programming and am stumped on this problem, Ive tried a few different ways with no success.
Implement (source code) a program (name it LargestOccurenceCount) that read from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the loop). The program should ignore any negative input and should continue to read user inputs until 0 is entered. The program should display the largest value and number of times it appeared
Scanner reader = new Scanner(System.in);
int num = 0;
int array[] = null;
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
array[num] = num;
}
Sample run 1:
Enter positive integers (0 to quit): 3 4 5 -9 4 2 5 1 -5 2 5 0
Largest value: 5
Occurrences: 3 times
The program should output the largest value entered and the number of times it was entered before 0 is entered.

You can use the following snippet:
// part of reading the values from command line and
// putting them into this array is omitted
int[] array = ...;
int biggest = 0;
int occurance = 0;
for(int num : array) {
if(num > biggest) {
biggest = num;
occurance = 0;
}
if(num == biggest) {
occurance++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
As mentioned in the comment, I've omitted the part where you read the values from the command line, as that doesn't seem to be your problem.
Another solution which does the reading directly, and without the need of an array and all inside one loop:
Scanner scanner = new Scanner(System.in);
int biggest = 0;
int occurance = 0;
int num;
while (true) {
System.out.print("Enter a number: ");
// this may throw an Exception if the users input is not a number
num = Integer.parseInt(scanner.nextLine());
if(num == 0) {
// user entered a 0, so we exit the loop
break;
}
if(num > biggest) {
biggest = num;
occurance = 1;
} else if(num == biggest) {
biggest++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);

Split your problem into two parts.
1. Find the largest value
int findLargest(int[] array) {
assert array.length > 0;
int result = array[0];
for (int element : array) {
if (element > result) {
result = element;
}
}
return result;
}
... and find it in the array
int countOccurences(int[] array, int value) {
int occurences = 0;
for (int element : array) {
if (element == value) {
occurences++;
}
}
return occurences;
}
Note that array should have at least one element;

If there is no requirements to use array only, you can use ArrayList for storing user inputs
List<Integer> list = new ArrayList<>();
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
list.add(num);
}
Then if you are good with stream api, there is quite concise solution:
Map.Entry<Integer, Long> lastEntry = list.stream()
.collect(groupingBy(Function.identity(), TreeMap::new, counting()))
.lastEntry();
System.out.println(
"Largest value: " + lastEntry.getKey() +
" Occurrences: " + lastEntry.getValue() + " times");

Related

the function doesn't take more than 10 letters on scanner

I need to get from the user the length and the value of the array and return the digit that shows the most times. for example: the user gave me the length "4" and the numbers {83,238,8,54} the function will return " the numbers that shows the most times is 8";
but it send an error massage if the user enter more than 10 digits in general.
String sum = "";
// get the length
System.out.println("Enter the size of the array :");
int size = in.nextInt();
// create the array
String[] arr = new String[size+1];
// get value
System.out.println("Enter the elements of the array:(max capity 10 digits) ");
for(int i=0; i<arr.length; i++) {
arr[i] = in.nextLine();
sum+=arr[i];
}
System.out.println("the numbers that you gave me are: "+sum);
int all = Integer.parseInt(sum);
System.out.println("the digit that shows the most time is: "+maxOccurring(all));
}
static int countOccurrences(int x,int d) {
int count = 0;
while (x > 0)
{
if (x % 10 == d)
count++;
x = x / 10;
}
return count;
}
static int maxOccurring( int x)
{
if (x < 0)
x = -x;
int result = 0;
int max_count = 1;
for (int d = 0; d <= 10; d++)
{
int count = countOccurrences(x, d);
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
}
```
You get an NumberFormatException at the following line:
int all = Integer.parseInt(sum);
Exception trace is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "25445648942"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at scan.ScannerTest.main(ScannerTest.java:27)
This exception is telling you that Integer.parseInt can't interpret the number you're passing through it (obtained by concatenating all the entered digits), in this precise example: "25445648942"
That's because this function is trying to yield an Integer from all those digits, which has a maximum capacity of 2^31 - 1 = 2,147,483,647. The entered number is higher that this, so it logically fails.
You should treat each entered number separately and count the digits in each, then do a sum of all to get your answer.
BTW, you don't ever need to convert to a number type to count the digits. It's simple string processing

Program is running but I get error when the user inputs integers

My program runs but I'm getting an error String index out of range: 3 When I enter 1 2 for example. I tried changing the values of 1 in partStr = str.substring(lastSpace + 1, x); but that didn't work. Any ideas what I'm doing wrong?
public static void main(String[] args) {
String str;
int x;
int length;
int start;
int num;
int lastSpace = -1;
int sum = 0;
String partStr;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
length = str.length();
for (x = 0; x <= length; x++) {
if (str.charAt(x) == ' ') {
partStr = str.substring(lastSpace + 1, x);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
lastSpace = x;
}
}
partStr = str.substring(lastSpace + 1, length);
num = Integer.parseInt(partStr);
System.out.println(" " + num);
sum += num;
System.out.println(" -------------------" + "\nThe sum of the integers is " + sum);
}
You should traverse upto length - 1.
The indexing in String is similar to what happens in arrays.If the length of String is 5 for example,the characters are stored in 0-4 index positions.
Your current loop is traversing beyond the size of the string.
str.length() will return the amount of characters of the string, let's say N
for(x = 0; x <= length; x++) will loop N+1 times, instead of N, because the index starts at 0 and you also enter the loop when x is equal to the length
replacing <= with < in the for loop will fix your problem
The issue you faced is because you tried to access a character at the index, x (i.e. str.charAt(x)) from str where x is beyond the maximum value of the index in str. The maximum value of the index in str is str.length - 1 whereas the for loop is running up to str.length. In order to fix that problem, you need to change the condition to x < length.
However, even after fixing that issue, your program may fail if any entry is non-integer or if there are multiple spaces in the input. A clean way, including exception handling, to do it would be as follows:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String str;
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a series of integers separated by spaces >> ");
str = keyboard.nextLine();
// Split str on space(s) and assign the resulting array to partStr
String[] partStr = str.split("\\s+");
// Iterate through partStr[] and add each number to sum
for (String num : partStr) {
try {
sum += Integer.parseInt(num);
} catch (NumberFormatException e) {
// Integer::parseInt will throw NumberFormatException for a non-integer string.
// Display an error message for such entries.
System.out.println(num + " is an invalid entry");
}
}
// Display the entries and the sum
System.out.println("Your entries are: " + Arrays.toString(partStr));
System.out.println("The sum of the integers is " + sum);
}
}
A sample run:
Enter a series of integers separated by spaces >> 10 a 20 10.5 30 b xy 40
a is an invalid entry
10.5 is an invalid entry
b is an invalid entry
xy is an invalid entry
Your entries are: [10, a, 20, 10.5, 30, b, xy, 40]
The sum of the integers is 100

Arithmetic mean in java

Problem statement
Need to find the Arithmetic mean of numbers entered by user.
Constraints
We cannot ask user to define/share the number of "NUMBERS" user has planned to enter i.e. we cannot ask user to tell how many numbers he is going to enter.
If -1 is entered by user, the input should stop and Arithmetic mean should be displayed.
We are supposed to ask user only to enter the numbers for which Arithmetic mean is to be calculated. Like : User enters
2
4
7
10
-1
so we need to calculate arithmetic mean for 2,4,7,10 and display the result.
Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
}while ( n != -1);
}
It goes to infinite loop and I've also tried using if/else but i didn't work. Please assist.
For the input of :
3
9
4
-7
0
2
-1
The arithmetic mean should be calculated for 3,9,4,7,0,2,29 i.e. 1.8
Try this:
Scanner sc = new Scanner(System.in);
int sum = 0;
int count = 0;
int n = 0;
do {
System.out.println("Enter next number(-1 to exit): ");
n = sc.nextInt();
System.out.println("Value is :" + n);
if(n != -1)
{
count++;
sum = sum + n;
}
}while ( n != -1);
sc.close();
System.out.println("Mean is: " + (double) sum/count);
}
You needed to move your sc.nextInt(); into the loop so that you can keep entering in values. I also added an if statement so the -1 does not get used in the mean value.
You're reading "n" as input out of the while, then n has always the first value and the loop is infinite.
You just need to keep passing ints, otherwise n is forever the first value entered.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
do {
System.out.println("Value is :" + n);
count++;
sum = sum + n;
n = sc.nextInt();
}while ( n != -1);

Print odd numbers in a descending order

The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}

Printing the two highest values from user input

I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
import java.util.Scanner;
public class ToStoersteTall{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
int biggest = 0;
for (int i = 3; i <= tall; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
biggest = num1;
if(biggest < num3){
biggest = num3;
}
}
System.out.println(biggest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
I have an assignment where I have to write a code which lets the user decide an amount of int values to be written in, and then decides what these values should be. There has to be atleast 2 inputs from the user. The program will then compare the values from the input and then print out the two highest values. So far I managed to print out the highest value, but I'm not sure whats wrong with the way I've done it since the output just becomes 0 if I choose to print out 2 numbers and the highest one is entered in first. And I'm also not sure how to keep track of the second highest number either. Would appreciate some help.
A couple things:
good practice to close scanner (and IO-related resources in general)
reduced if-statement blocks bloat for easier readability
you specify 2 guaranteed numbers, so attempt to parse those before looping
can remove system.exit calls or replace system.exit and move bulk of code back into the larger if-else blocks as originally state in OP (but I refer back to the sake of readability)
added check for the first and second numbers input to make sure high1 is highest value, and high2 is second highest value.
keep order while looping and checking values (note: does not use array), if the number is a new high, replace high1 and move high1's value down to high2, or if the number is a second (new) high, replace high2. If values are equal, this logic is excluded and you may want to specify based on your own constraints
import java.io.IOException;
import java.util.Scanner;
public class ToStoersteTall {
public static void main(String[] args) throws IOException {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
int n = 0;
if (reader.hasNextInt()) {
n = reader.nextInt();
} else {
System.out.println("Vennligst oppgi et heltall større eller lik 2.");
System.exit(-1); // quits execution
}
if (n < 2) {
System.out.println("Please enter an integer equal or higher than 2.");
System.exit(-2);
}
// Since guaranteed 2 numbers, parse and assign now
int high1 = 0, high2 = 0;
System.out.println("Enter value # 1");
if (reader.hasNextInt())
high1 = reader.nextInt();
System.out.println("Enter value # 2");
if (reader.hasNextInt())
high2 = reader.nextInt();
// check to see if a switch to keep correct highest order, swap values if so
if (high1 < high2) {
int t = high2;
high2 = high1;
high1 = t;
}
// loop won't execute if only 2 numbers input, but will if 3 or more specified at start
for (int i = 2; i < n; ++i) {
System.out.println("Enter value #" + (i + 1));
if (reader.hasNextInt()) {
int t = reader.nextInt();
if (t > high1) {
high2 = high1; // throw away high2 value and replace with high1
high1 = t; // replace high1 value with new highest value
} else if (t > high2) {
high2 = t;
}
} else {
System.out.println("Please enter an interger");
}
}
reader.close();
System.out.println("The two highest numbers are: " + high1 + ", " + high2);
}
}
You're already keeping track of the biggest, so why not keep track of the second biggest? Another easy way of solving this problem is to keep all the numbers in a list, sort the list by number size, and grab the two highest entries.
I tried your code and used an array to solve the problem.
import java.util.Scanner;
public class Main {
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
public static void main(String[] args) {
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if (reader.hasNextInt()) {
int numbers = reader.nextInt();
int[] array = new int[numbers];
if (numbers >= 2) {
System.out.println("Enter value #1");
if (reader.hasNextInt()) {
int num1 = reader.nextInt();
array[0] = num1;
System.out.println("Enter value #2");
if (reader.hasNextInt()) {
int num2 = reader.nextInt();
array[1] = num2;
int biggest = 0;
for (int i = 3; i <= numbers; i++) {
System.out.println("Enter value #" + i);
int num3 = reader.nextInt();
array[i-1] = num3;
}
System.out.println("second largest number is" + secondHighest(array));
int largest = 0;
for(int i =0;i<array.length;i++) {
if(array[i] > largest) {
largest = array[i];
}
}
System.out.println("Largest number in array is : " +largest);
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer");
}
} else {
System.out.println("Please enter an integer equal or higher than 2.");
}
} else {
System.out.print("Vennligst oppgi et heltall større eller lik 2.");
}
}
}
Test
How many numbers? (minimum 2)?:
6
Enter value #1
3
Enter value #2
4
Enter value #3
5
Enter value #4
6
Enter value #5
7
Enter value #6
8
second largest number is7
Largest number in array is : 8
There is a logic error in your program. If numbers is 2, then the for loop never gets executed, and the value of biggest remains zero because it is never updated. Change your declaration of biggest to reflect the current maximum value found so far.
int biggest = num1 > num2 ? num1 : num2;
That way if the for loop never executes then biggest will be the maximum value of the first two numbers.
As for keeping track of the second highest value, you could introduce another variable secondBiggest, initialised in a similar manner to biggest, and then write logic to update this value in your for loop. However, in my opinion, it would be much easier to change your strategy to hold the entered values into an array, then when all inputs have been entered, calculate whichever values you desire from the array. This would lead to a much cleaner solution IMO.
(I have assumed that tall in the for loop is actually meant to be numbers...)
import java.util.Scanner;
public class Foo{
public static void main(String[] args){
System.out.println("How many numbers? (minimum 2)?:");
Scanner reader = new Scanner(System.in);
if(reader.hasNextInt()){
int numbers = reader.nextInt();
if(numbers >= 2){
int[] list = new int[numbers];
for(int i = 0; i < numbers; i++){
System.out.println("Enter value #" + (i + 1));
if(reader.hasNextInt())
list[i] = reader.nextInt();
}//for
int biggest = 0;
int secondBiggest = 0;
// find the values you want
for(int i = 0; i < numbers; i++){
if(list[i] > biggest){
secondBiggest = biggest;
biggest = list[i];
}//if
else if(list[i] > secondBiggest)
secondBiggest = list[i];
}//for
// print your results
System.out.println("The biggest integer is: " + biggest);
System.out.println("The second biggest integer is: " + secondBiggest);
}//if
}//if
}//main
}//class

Categories