This is what i've got so far, but can't figure out how to display the number of
numbers the user enters, I know it has something to do with the count method, but can't figure out how to implement it into this.
import java.util.Scanner;
public class Test {
#SuppressWarnings("resource")
public static void main(String[] arg) {
int count = 0;
double sum = 0;
double maximum = 0;
double minimum = 100;
Scanner kb = new Scanner(System.in);
double input = -1;
// Main processing loop...
do {
// Validation loop...
do {
System.out.println("Please enter a number or 0 to quit:");
input = kb.nextDouble();
kb.nextLine();
} while (input > 100);
if (input > 0) {
count++;
sum += input;
if (maximum < input) {
maximum = input;
}
if (minimum > input) {
minimum = input;
}
}
} while (input != 0);
double average = (sum / count);
System.out.println(
"The average is: " + average);
System.out.println(
"Minimum of entered numbers: " + minimum);
System.out.println(
"Maximum of entered numbers: " + maximum);
}
}
Add the entered items to a List.
You create a list with:
List<Integer> list = new ArrayList<>();
And you add an item to the list with:
list.add(input);
Finally you have the collection of all the inputs and better to work with.
The advantage is you can return back to all the inputs and work with them again.
To get the size you can use both of:
System.out.println(count); -- using your variable
System.out.println(list.size()); -- get from the list
If you're trying to work with the input you need to save it somewhere. An array would be your best choice (array, ArrayList, ...).
Iterate through the array to get the lowest and highest number.
Divide the sum of all numbers by the size of the array to get the average.
EDIT: If you want to add negative numbers change if (input > 0) to if (input != 0) (I'm guessing you're adding the input into the array from here).
just change the if condtion logic use if (input != 0 ) { instead of if if(input > 0 )
try like below.
if (input != 0 ) {
....
}
System.out.println("User enters total Numbers: "+count);
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 want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"
Here's what my program is supposed to do:
This is a program with a loop that lets the user enter a series of integers. The user should enter -99 to signal the end of the series. After all the numbers have been entered, the program should display the largest and smallest numbers entered.
My code is working but right before it stops it initializes either the max or min as the -99, instead of the last intended integer in the series, then ends. What can I do to stop that?
Here's the code:
public static void main(String[] args)
{
//Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//create variables
int maxInt = -1000; //number that will be the largest initialized very low
int minInt = 1000; //number that will be the smallest initialized very high
int input = 0; //to hold the user's integer entry
//loop for the user to enter as many integers as they want
while(input != -99)
{
//General Instructions and initialization of input
System.out.println("Enter an integer. "
+ "When you are finished, please enter -99.");
input = keyboard.nextInt();
if(input > maxInt)
{
maxInt = input;
}
else if(input < minInt)
{
minInt = input;
}
}
System.out.println("Your lowest number is: " + minInt);
System.out.println("Your highest number is: " + maxInt);
keyboard.close();
}
Your input is assigned inside your while-loop thus not yet -99 when the loop starts. Therefore runs the loop with -99 and then stops at the end.
while (input != -99) {
System.out.println("Enter an integer. " + "When you are finished, please enter -99.");
input = keyboard.nextInt());
if (input == -99) {
break;
}
if (input > maxInt) {
maxInt = input;
} else if (input < minInt) {
minInt = input;
}
}
Now the loop ends when there is a input of -99 due to the break statement.
You need to check the input value before assigning the maxInt or minInt variable for -99 if it is your sentinel control value.
Example
if ( input > maxInt && input != -99 )
{
maxInt = input;
}
else if ( input < minInt && input != -99 )
{
minInt = input;
}
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.
I am trying to get the average of user inputted numbers. Every time I input numbers the output is always-
The sum is 6
How many numbers: 4
Average: 2.0
A while loop is required, unfortunately for loops are not allowed. I am pretty new to Java so my formatting is sloppy. Where in my code are my problems?
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += count;
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
You have several errors here.
The main one that causes your error is sum += count. Instead of adding what the user has entered, you are adding the number that shows how many numbers there are. So it will always add 0+1+2+3 etc.
Another problem is that, once you change the above, you have to check whether the input == endingVariable before you add the input to the sum. So you have to write the if first, and then calculate the average inside it. Otherwise it will treat your -1 as part of the sequence of numbers to calculate.
You only need to add the input to the sum and increment the count if you find out that the input is not yet the same as endingVariable.
So:
Add the input, not the count, to the sum.
Calculate the average only when you have reached the final item.
Add the input to the sum and increment the counter only if your input is not endingVariable.
Try this one...
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
// program in this project exercises 36.1-36.5
// actually this is just one program that is split in many parts
Scanner reader = new Scanner(System.in);
int count = 0;
int sum = 0;
int endingVariable = -1;
int input = 0;
double average;
while (input >= endingVariable) {
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
sum += input; // you were doing mistake here.
average = (double)sum / count;
count++;
if (input == endingVariable) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
}
}
}
}
Two big issues with your code. First, this line:
sum += count;
It's probably just a typo, but it should be obviously:
sum += input;
Second, once you fix that, you will notice you are including the -1 in your sum. You probably want something like this:
System.out.println("Type numbers: ");
input = Integer.parseInt(reader.nextLine());
if (input == endingVariable) {
average = (double) sum / count;
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + count);
System.out.println("Average: " + average);
break;
} else {
sum += input;
count++;
}
Thank you for explaining in detail. It works fine now, all I had to do was what you said is change the input, and move the sum += input and count after the final item in an else. I was having the hardest time trying to figure out why my -1 was being included