How to find max number and occurrences - java

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}

So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}

The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.

You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}

Related

Getting max value of N inputs without using arrays

I'm struggling with an exercise to find the max input of N values. I'm being able to print the max value but the exercise asks to print ONLY the max value and I'm not being able to return it from outside the IF statement.
Exercise's instructions:
Write a program that:
reads a number N (must be greater than 0) from the console
reads N numbers from the console
Displays the maximum of the N entered numbers.
My code:
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i=0;
int count=1;
int max=Integer.MIN_VALUE;
for (i=0; i<count; i++) {
int cur = sc.nextInt();
count++;
if (cur>0){
if (cur>max) {
max=cur ;
System.out.println(max);
}
}
}
}}
In the console I'm getting the desired inputs plus this error
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
First of all, you must import java.util.Scanner when you using Scanner class.
I changed some lines of your code, I think this is what you want:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // get N (how many numbers)
int number;
int max = Integer.MIN_VALUE;
if (n > 0) {
for (int i = 0; i < n; i++) {
number = sc.nextInt(); // get numbers
if (number > max)
max = number;
}
System.out.println(max); // print the maximum number
} else
System.out.println("Please enter greather than 0 number"); // when n is negative or zero
}
}
You should read the exercise carefully. First, you must read the N number to determine how many numbers should be read from the console in total.
Also you must handle the exception cases with try-catch blocks that might be thrown during reading or parsing. Try this one:
Playground: https://repl.it/repls/OrnateViolentSoftwaresuite (it might take some time to load).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 1. reads a number N (must be greater than 0) from the console
int N = 0;
while(N == 0) {
try {
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}
}
// 2.reads N numbers from the console
int max = Integer.MIN_VALUE;
for (int i = 0; i < N; i++) {
while(true) {
try {
System.out.printf("Enter %d. number: ", i + 1);
// determine the max during reading
max = Math.max(max, Integer.parseInt(sc.nextLine()));
break; // cancels while(true)
} catch (Exception ignored) {}
}
}
// 3. Displays the maximum of the N entered numbers
System.out.printf("The max number is %d\n", max);
System.out.println("Goodbye!");
sc.close(); // don't forget to close the resource
}
Update
If you really haven't learned the try / catch yet, then you don't have to use it either. You can simply remove the try-catch blocks from the above code, which should also work (for valid integer inputs only)
e.g. instead of
try {
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}
just use
System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());
Ok, this is how I solved it. Initially I wasn't understanding that the first input was the number of inputs. Once I understood that, it became a bit easier.
Basically I had to tell the program to only print the max number after the last input (n-1). Thanks to all that helped.
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // get N (how many numbers)
int number;
int max=Integer.MIN_VALUE;
for (int i=0; i<n; i++) {
number = sc.nextInt();
if (number>max) {
max=number ;
}
if (i==n-1)
System.out.print(max);
}
}
}
Here's a step by step explanation.
Read in a number N (N > 0)
int n = sc.nextInt();
Check for N > 0
if (n <= 0) {
System.out.println("Must be > 0, please try again.");
}
To continually do this, use a while loop.
int n = -1;
while (n <= 0) {
n = sc.nextInt();
if (n <= 0) {
System.out.println("Must be > 0, please try again.");
}
}
Now find the max.
// initialize to first value
int max = sc.nextInt();
Now get the others
// start from 1 since we already have a value
for(i = 1; i < n; i++) {
int v = sc.nextInt();
// if current value is greater than max
// replace max with current value
if (v > max) {
max = v;
}
}
Print the answer.
System.out.println("max = " + max);

how do i repeatedly multiply a number in java by 2 until it reaches 1 million?

import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}

Count How many number multiple by the number from input user between a range

again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

Java scanner count numbers that are in an interval

I'm new with java and i have to write a code that asks the user two numbers an interval. Then the user must introduce n numbers and the program must return how many numbers belong to that interval.
I've tried to do this and this is what i have:
import java.util.*;
public class NumsInter {
public static void main(String[] args) {
Scanner sc;
int a,b,nums,count;
sc = new Scanner (System.in);
System.out.print ("Write two numbers a and b(a<=b)(interval): ");
a=sc.nextInt();
b=sc.nextInt();
count=0;
System.out.println("write a number: ");
while(sc.hasNextInt()){
nums=sc.nextInt();
if (a<=nums && nums>=b){
count= count + 1;
} else {
count= count;
}
}
System.out.println(count +" numbers are included in ("+a+","+b+")");
}
}
Example: If the user writes 2 and 6, and then 4,4,3,1 the output should be 3.
As I am a newbie i don't know how can i do this the good way, can someoen help?
PD: How can i break the loop so i can get the output?
Thank You!
Try something like this
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Enter the numbers you want to test, enter 'stop' to stop");
boolean userInput = true;
while(input.hasNextInt() && userInput){
if(input.hasNext("stop")){userInput = false;}
numbers.add(input.nextInt());
}
Where you have a loop that checks if there is a next int while at the same time checking to see if the user is done or not.
And them something like this to print your answer
for(int i =0; i < numbers.size(); i++){
testNum = numbers.get(i);
if(testNum > lowerLimit && testNum < upperLimit){
count++;
}
}
System.out.println(count + " valid numbers have been entered!");
take an int [] no_between_max&min after take the input from user and store in this array. after that take a for loop and compare the value of array with max and min ant increase the count variable.
int noOfItem=sc.nextInt();
int [] no_between_max_min = new int[noOfItem];
for(int i=0;i<noOfItem;i++){
no_between_max_min[i]=sc.nextInt();
}
for(int i=0;i<no_between_max_min.length;i++){
if(no_between_max_min[i]>=a&&no_between_max_min[i]<=b){
count++;
}
}

How do i exclude negative numbers in an if loop?

For my project, the user enters a set of numbers, and some calculations are performed to give the desired output. One of the calculations is the find the sum of the odd numbers that are inputted. Looking at the given test cases, I noticed my code was adding the negative odd numbers, while the correct test cases do not. Is there any easy fix for this?
Thanks
Here is some of the code, what I have written minus a few parts.
import java.util.Scanner;
public class Test
{
public static void main (String[] args)
{
int min_interger = 0;
int sum_of_pos = 0;
int sum_of_odd = 0;
int count_of_pos = 0;
int userInput;
Scanner consoleInput = new Scanner(System.in);
do {userInput = consoleInput.nextInt();
if(userInput % 2 != 0)
{
sum_of_odd = sum_of_odd + userInput;
}
while (userInput != 0);
System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}
}
Make sure to add odd and greater than zero numbers
if(userInput % 2 != 0 && userInput > 0)
{
sum_of_odd = sum_of_odd + userInput;
}

Categories

Resources