Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 0;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
I would like to be able to find the occurrence of the largest int, and I am not sure how to go about doing so, in a rather simple way. I tried adding occurrence++; under largest = number;, but that did not work.
For example, I would type 6 as input, and I would get random numbers 54, 74, 61, 89, 13, 89.
The desired output would be max is 89. Occurrence is 2.
Also, I am trying to only get the code to print only 10 numbers per line, then it would skip to the next line and continue.
In case of reoccurrence, increase occurrence variable;
set occurrence to 1 in case of new larger number
You can use
if(number > largest){
largest = number; // found larger value
occurrence = 1; // reset occurrence back to initial
}else if(number == largest){
occurrence++; // keep track of same large value
}
You need to use an else if condition to check equality like this
Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 1;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}else if(number == largest){
occurrence++;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
P.S - Initialize occurrence = 1 as there will be at least one time the largest number will be present
I think you are almost there. Basically, you are missing a check on whether the new random number is equal to the current largest number. Something like:
if (number == largest) {
occurrences++;
}
Also, remember to reset occurrences when a new largest number has been found:
if (number > largest){
largest = number;
occurrences = 1;
}
Related
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");
I'm trying to determine how many times the number four appears in a sequence of numbers. There is a lower bound and upper bound (inclusive) that the user can determine. My code so far only counts the number of times the number 4 occurs if the range is set 40-49-- the resulting output is 10, however the actual value should be 11 because 44 has two 4's. In addition, the output for a range of 1-10 should be 1 but instead I get a value of zero? Am I not properly checking for the occurrence of 4? I'm taking into account the difference places (one's, tenths, hundredths place).
Scanner scan = new Scanner(System.in);
int count = 0;
int i;
System.out.println("Enter the lower range: ");
int lower = scan.nextInt();
System.out.println("Enter the upper range: ");
int upper = scan.nextInt();
if (lower > upper) {
System.out.println("Bad input");
}
for (i = lower; i <= upper; i++) {
if (lower * 0.01 == 4) {
count++;
} else if (lower * .1 == 4) {
count++;
} else if (lower * 1 == 4) {
count++;
}
}
System.out.println("Result: " + count);
Don't use floating point math. The results are subject to accuracy errors. Stick to integer arithmetic.
Hint: Use modulus % and division / to pull out particular digits.
Below Java Code will solve your problem:
try (Scanner scan = new Scanner(System.in)) {
int count = 0;
int i;
System.out.println("Enter the lower range: ");
int lower = scan.nextInt();
System.out.println("Enter the upper range: ");
int upper = scan.nextInt();
if (lower > upper) {
System.out.println("Bad input");
} else {
int num=0;
for (i = lower; i <= upper; i++) {
num=i;
while(num>0){
if(num%10==4){
count++;
}
num=num/10;
}
}
System.out.println("Result: " + count);
}
}
Note: When IF execute it not means below code will not execute. just write else part or exit program.
I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.
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
So my code works in all test cases except for when there are only two integers.
Example if user inputs: terminating number as -1 and then inputs 1,2 and then -1 again the smallest numbers are 1,1 and not 1,2
Terminating number is just the way to end the sequence/program.
public static void main(String[] args) {
double num;
double min = 0;
double min2 = 0;
System.out.println("Enter terminating value:");
int term = IO.readInt();
System.out.println("Enter next value:");
num = IO.readDouble();
if(num == term){
IO.reportBadInput();
main(args);
}
int count = 0;
min = num;
min2 = num;
do{
num = IO.readDouble();
if(num!= term && num < min) {
min2 = min;
min = num;
}
else if (num!= term && num < min2) {
min2 = num;
}
count++;
}while (num != term);
if(count < 2){
IO.reportBadInput();
main(args);
}
else{
IO.outputDoubleAnswer(min);
IO.outputDoubleAnswer(min2);
}
}
The issue with your code lies in setting both minimal values to the number that was first entered. This is bad because if the user enters the smallest value first, both min and min2 already contain the minimum value. That means the condition input < min2 is always false, causing min2 to always contain the value the user has entered first.
To fix this, simply set the value of min2 to a value which is larger than any other value the user could enter (for example Double.MAX_VALUE or Double.POSITIVE_INFINITY).
Just as a hint concerning the error-handling part of your code: if you call main again after reminding the user that their input was invalid, make sure to add a return behind that call or the execution will continue after the called main method is finished. Something like this:
if (count < 2) {
IO.reportBadInput();
main(args);
return;
}