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);
Related
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);
}
I have this assignment and I am stuck, please help, I'm sure it'll be quick. Please help!
This is my prompt:
Write a method minMax( ) that has a int type parameter that represents how many integers you want to enter. It will input that many integers and will print the minimum and maximum values among the entered values.
minMax(5) will input 5 integer values and print the minimum and maximum values of the entered values.
I've tried to check the questions related to my topic, however, they were far too complicated. This is simple code.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
//call your method here
}
public static int minMax(int num){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a value: ");
int num = scan.nextInt();
int min = num;
int max = num;
for(int i = 1; i < ; i++){
}
}
}
Here is quick fix for you.
Please check following code to get min and max value from all element list.
Input :
Please enter value of N:
5
Please enter 5 numbers
4
2
10
156
2
Output :
Max of N number is : 156
Min of N number is : 2
public static void main(String arg[]) {
Scanner scan = null;
int n = 0;
int max = 0,min = 0;
try {
System.out.println("Please enter value of N: ");
scan = new Scanner(System.in);
n = scan.nextInt();
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
System.out.printf("Please enter %d numbers %n", n);
for (int i = 0; i < n; i++) {
int current = scan.nextInt();
if (current > max) {
max = current;
}
if (current < min) {
min = current;
}
}
System.out.println("Max of N number is : " + max);
System.out.println("Min of N number is : " + min);
}
catch (Exception ex) {
ex.printStackTrace();
}finally{
scan.close();
}
}
Hope this solution works.
Please mark as answer if this solution helpful.
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.
I want to validate the data type, (in my case it is 'int'), at the time of user input using Scanner.
I wrote code below.
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of an array...");
int n = 0;
// 1st block, n <= 100
do {
System.out.println("Capacity must be less than or equal to 100");
try {
n = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Enter only integers ");
}
} while (n > 100);
int[] arr = new int[n];
// block 2. Value must be greater than 0 and less than 10000
for (int i = 0; i < n;) {
do {
try {
arr[i] = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Enter only integer value");
}
} while (arr[i] > 10000 || arr[i] < 1);
i++;
}
scanner.close();
for (int i = n - 1; i >= 0; i--)
System.out.println(arr[i]);
}
}
Issue is,
in 1st block, if i give character, program terminates. "How to keep loop running on failed validation??"
in 2nd block if i give non integer, it runs infinitely with message, "Enter only integer value".
From debug, i conclude that, Without waiting for input it takes last non-int value which was provided before.
Why compiler is taking last value??
Any suggestion ?
1) You assign 0 as default value of the n integer you are using to get the user input : int n = 0;
So if the input triggers a InputMismatchException, you arrive in the while statement with a n that equals 0 and while (n > 100) with n = 0 is false.
So you exit the loop.
To solve this problem :
use a wrapper Integer : Integer n = null; that has a nullable value allows to know if no value was accepted in the scanner reading
change the while statement condition to check your requirement :
while (n == null || n > 100);
2) For first case as for the second case, if the input doesn't match with the type required (here a int value), the current token in the scanner is not read.
Just ignore this token to avoid entering in an infinite loop :
catch (InputMismatchException e) {
...
scanner.nextLine();
}
As an addition to davidxxx's answer:
Here's the same code using Scanner.hasNextInt() method.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of an array...");
while (!scanner.hasNextInt()) scanner.next();
int arrayLength = scanner.nextInt();
int[] arr = new int[arrayLength];
boolean arrayFull = false;
int index = 0;
System.out.println("Enter array values");
while (!arrayFull){
while (!scanner.hasNextInt()) scanner.next();
int value = scanner.nextInt();
if (value < 0 || value > 1000) {
System.out.println("Enter only integer value < 0 and > 1000");
continue;
}
arr[index++] = value;
if (index >= arrayLength){
arrayFull = true;
}
}
I am a beginner and i wrote a java program that allows you to enter n numbers and it displays the max, min and average only if the number -5 is entered, my program its not displaying correctly and i need some help. I want to use try/catch to catch errors when a string is entered instead integer.
import java.util.Scanner;
public class Average{
public static void main(String[]args){
System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");
System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}
To get integer inputs in a loop, respond to an "exit" value, and guard against invalid inputs, I would use something like the template below.
Note that something critical that none of the answers so far has mentioned is that it is not good enough to simply catch InputMismatchException. You must also call your scanner object's nextLine() method to clear the bad input out of its buffer. Otherwise, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next() instead depending on the circumstance, but know that input like this has spaces will generate multiple exceptions.
Code
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter integers or -5 to quit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
Example
Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...
You would probably want
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
inside the while loop because right now you are only checking the last read value(also, there's no need to up the counter outisde the loop(after you have read -5, btw, why -5?o.O).
Also, you would probably want the min/max values initialised this way, because if your min value is bigger than 0, your code outputs 0. Same goes if your max value is below 0:
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
For the non-integer part: read up on exceptions and use a try-catch block to catch the InputMismatchException.
try {
//while(scan.nextInt) here
} catch (InputMismatchException e) {
//Do something here, like print something in the console
}
As someone else pointed out, if you want the average to not be truncated, cast sum to double: ((double) sum) / count.
Finally, but most important: try debugging it yourself before asking someone else.
Try this:
import java.util.Scanner;
public class Average {
static Scanner scan;
public static void main(String[] args) {
System.out.println("Enter any integer numbers or -5 to quit:");
scan = new Scanner(System.in);
int number = -1, sum = 0, count = 0;
int max = 0;
int min = 0;
while((number = scanNextInt()) != -5) {
count++;
sum = sum + number;
if(number > max) {
max = number;
}
if(number < min) {
min = number;
}
}
if(number == -5) {
try {
System.out.println("Average : " + (sum / count));
System.out.println("Maximum : " + max);
System.out.println("Minimum : " + min);
}catch(Exception e) {
//Error printing, so quit the program. Look below.
}
//Quit
System.exit(0);
}
scan.close();
}
static int scanNextInt() {
try {
return scan.nextInt();
}catch(Exception e) {
//Stop the program if the user inputs letters / symbols
System.out.println("Invalid Number.");
return -5;
}
}
}
Changes I've made:
1. I've created a method called scanNextInt() that returns scan.nextInt() if possible. If it will cause an error, it returns -5 to stop the program.
2. I've included the two if statements in the while loop so they actually work.
3. I've caught all of the possible errors, so you should not see any error messages
Note: This HAS been tested
Firstly - you need to move the closing bracket of the while loop after the min number check to allow the checks to be performed for every number you read. And remove one count++ to avoid double counting.
To ignore illegal input you could use one of the other Scanner methods and read a String instead of int, then try to Integer.parseInt the String and wrap the parsing into a try catch.
//count++;
double avg = 0.0;
if (count != 0) {
avg = ((double) sum) / count;
}
System.out.println("Average : " + avg);
When both sides of the division are int then it is an integer division (result int, remainder of division thrown away).
Hence we cast one side, here sum to floating point:
(double) sum
And then it works.