User input only occurs once or never stops during loop - java

I am attempting a program that reads an unspecified number of integers, find sum, positive, negative and average. My issue is that either it will only run and allow one integer to be typed and then do nothing, or with the following code, it never stops letting you enter numbers therefore I can't get past. I have the number = 0 output correct.
public class Compute {
// Count positive and negative numbers and compute the average of numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
positive = 0;
negative = 0;
total = 0;
System.out.println("Enter an integer, the input ends if it is 0: ");
int numbers = input.nextInt();
do {
if (numbers > 0) {
positive++;//add 1 to positive count
} else if (numbers < 0) {
negative++;//add 1 to negative count
}//end else if
sum += numbers; //add integer input to sum
numbers = input.nextInt();
total++;
} while (numbers != 0);
if (numbers == 0) {
System.out.println("No numbers are entered except " + numbers);
}//end if
}
}

Try below code. to terminate the loop and see output type 0 as input at any time of execution.
import java.util.Scanner;
public class Compute {
// Count positive and negative numbers and compute the average of numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sum = 0;
int positive = 0;
int negative = 0;
int total = 0;
System.out.println("Enter an integer, the input ends if it is 0: ");
int numbers = input.nextInt();
do {
if (numbers > 0) {
positive++;// add 1 to positive count
sum += numbers; // add integer input to sum
}
else if (numbers < 0) {
negative++;// add 1 to negative count
sum -= numbers; // add integer input to sum
}
numbers = input.nextInt();
total++;
} while (numbers != 0);
System.out.println("The number of positives is \t " + positive);
System.out.println("The number of negatives is \t " + negative);
System.out.println("The total count of number is \t " + total);
System.out.println("The sum of all number is \t" + sum);
System.out.println("The average is \t"
+ ((double) sum / (positive + negative)));
}// end main
}// end Compute

Following code snippet should give you a good example on how to read integers from console:
Scanner scanner = new Scanner(System.in);
do {
int i = scanner.nextInt();
// ...
} while (scanner.hasNext());
The scanner.hasNext() method call will block until user enter the next number on console

Related

while loop in java giving wrong outputs and not working correctly

Im trying to get specfic outputs using these inputs:1 2 2 1 3 -1. The ouputs are suppose to be Count of positive integers is: 5
The highest value is: 3
The lowest value is: 1
The average is: 1.8
HOwever, im keep getting the wrong outputs for low and average value
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num, max, low, sum;
num= scnr.nextInt();
max = num;
low =0;
sum=0;
int count = 0;
double avg=0;
while(num>=0 )
{
num=scnr.nextInt();
if(num<max)
{
low = num;
}
else
{
max=num;
}
sum+= num;
count++;
}
avg=(double)sum/count;
System.out.println("Count of positive integers is: "+count);
System.out.println("The highest value is: "+max);
System.out.println("The lowest value is: "+low);
System.out.println("The average is: "+ avg);
}
}
For the suggested changes, I will stick to your code structure and you can further refine it:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num, max, low, sum;
num = scnr.nextInt();
max = num;
// Should not set low = 0, you should set low to the first read number also
low = num;
// You have already read one number above, sum should start from num
sum = num;
// You have already read one number above, count should start from 1
int count = 1;
double avg = 0;
while (num >= 0)
{
num = scnr.nextInt();
// You have to stop while loop if num < 0, you do not want to count negative number
if (num < 0)
break;
// If you have number smaller than low, set it
if (num < low)
low = num;
// If you have number bigger than max, set it
if (num > max)
max = num;
sum += num;
count++;
}
avg = (double)sum / (double)count;
System.out.println("Count of positive integers is: " + count);
System.out.println("The highest value is: " + max);
System.out.println("The lowest value is: " + low);
System.out.println("The average is: " + avg);
}
}
But note that there is a flaw for the above code if your input is only -1. I will leave this to you to have a try on how to fix that.

Tutorial test for calculate average fails: output shouldn't contain: 0

i'm new here learning java and on the site that i'm learning on one of the tests i cannot pass because of this error
When input was:
>1
2
0
output shouldn't contain:
>0
the test is
Write a program that asks the user for input until the user inputs 0. After this, the program prints the average of the positive numbers (numbers that are greater than zero).
If no positive number is inputted, the program prints "Cannot calculate the average"
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int inputs = 0;
int sum = 0;
double average = 0;
while (true) {
System.out.println("Give a number:");
int number = Integer.valueOf(scanner.nextLine());
if (number > 0) {
inputs++;
sum += number;
average = (double)sum / inputs;
System.out.println(average);
} else if (number <= 0) {
System.out.println("Cannot calculate the average");
}
if (number == 0) {
break;
}
}
}
}
Find what worked for me below:
import java.util.Scanner;
public class AverageOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//Task is to keep count of positive integers, sum and calculate average
double pNumbers = 0;
int sum = 0;
//Task is to read user input and assign a variable
while (true) {
//Task is to prompt user for input
System.out.println("Enter number:");
int number = Integer.valueOf(scanner.nextLine());
//Task is to terminate the program when user inputs 0
if (number == 0) {
break;
}
if (number > 0) {
pNumbers = pNumbers + 1;
sum = sum + number;
}
}
//The task is to calculate the average
//print only if user has given numbers and avoid dividing by zero
if (sum + pNumbers > 0) {
double average = (sum / pNumbers);
System.out.println(average);
} else {
System.out.println("Cannot calculate the average");
}
}
}

How to calculate the average of a sequence of integer numbers read from the console?

What is missing in my code in order to calculate the average of the inputted numbers from the user?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
float average;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
} while (n != 0);
if (n == 0) {
System.out.println("The average is : " + n);
}
scanner.close();
}
}
When the user puts in "0" then the programm should calculate the average of the inputted numbers by the user, that is why i wrote "while (n != 0)".
You should do something like this:
Note that as you have one more number (the zero), then you have to consider it when calculating the average by removing it, because you ask for 0 to finish the program.
public class Teste {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
double average = 0;
int qtdNums = 0;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
average = average + n;
qtdNums++;
} while (n != 0);
if (n == 0) {
System.out.println("The average is : " + average / (qtdNums - 1));
}
scanner.close();
}
}
You are not actually using the numbers that you are reading in. A good editor would tell you that before you even ran it. I would look into getting the Eclipse IDE. You will want to do something similar to that suggested by jhenrique. I would say it is probably better to add the numbers as integers and then cast later, so that you do not lose accuracy on floating point additions, which can cause you a lot of grief in some cases (but here you are probably fine). Here is my suggested code, modified from jhenrique's answer:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
int sum = 0;
int count = 0;
do {
System.out.print("Enter a number: ");
n = scanner.nextInt();
System.out.println("Your number is " + n);
sum += n;
count++;
} while (n != 0);
System.out.println("The average is : " + ((double) sum) / (count - 1));
scanner.close();
}
double is like float, but more accurate. In the loop, I add each read number to sum and then divide by the number of things read at the end to get the average.

Count Even and Odd Numbers User has Inputted - java

Hi this is what a question on a course I am doing wants...
The program prints "Type numbers” until the user types the number
-1. When the user types the number -1, the program prints "Thank you and see you later!" and ends
the program should print the sum of the numbers entered by the user
(without the number -1).
the program should print how many numbers the user typed (without
the number -1).
the program should print the average of the numbers the user typed
(without the number -1).
5. the program should print the number of even and odd numbers that the
user typed (without the number -1).
I have completed 1-4 but am completely stuck on 5. I did make a start on trying to work it out including putting a for loop inside my while loop but apart from the fact it didnt work it looked well out of place so i removed it. Anyway here is what i have done so far which as I say all works in its own magical way.
And so if anyone can help me with question 5 that would be great. ps.I'm sure what i've done so far could have been written better but don't focus on that for now cos for me and where i am with Java this is nothing short of a miracle.x
import java.util.Scanner;
public class LoopsEndingRemembering {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int sum = 1; // to counteract the -1 from the user
int total = 0;
double avg;
//int even = 0;
//int odd = 0;
System.out.println("Type numbers:");
while (true) {
int numbers = Integer.parseInt(reader.nextLine());
sum += numbers;
total++;
avg = ((double) sum) / (total - 1);
if (numbers == -1) {
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum);
System.out.println("How many numbers: " + (total - 1));
System.out.println("Average: " + avg);
//System.out.println("Even numbers: " + even);
//System.out.println("Odd numbers: " + odd);
break;
}
}
}
}
You could store variables where one counts odd numbers and one counts even numbers. If the number is odd, increment the odd numbers variable. If even, increment the even numbers variable. Use the % operator to get the remainder of the input divided by 2.
int oddNumbers = 0;
int evenNumbers = 0;
if(numbers % 2 == 1){
oddNumbers++;
} else if(numbers % 2 == 0){
evenNumbers++;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner (System.in);
int sum = 0;
System.out.print("Enter limit number: ");
int limit = in.nextInt();
int oddNumbers = 0;
int evenNumbers = 0;
for(int i= 1;i<=limit;i++)
{
System.out.println("Enter limit number: "+i+"");
int numbers= in.nextInt();
if(numbers %2==0)
{
evenNumbers++;
}
else if(numbers %2==1)
{
oddNumbers++;
}
}
System.out.println("There are: "+oddNumbers+" odd numbers");
System.out.println("There are :"+evenNumbers+" even numbers");
}
}
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
int firstnum = 4;
int lastnum = 104;
int evncnt, oddcnt;
int count;
System.out.println("First number is " + firstnum);
System.out.println("Last number is " + lastnum);
count = lastnum - firstnum + 1;
System.out.println("Total numbers are " + count);
if (count % 2 == 0) {
System.out.println("Total even numbers are " + count / 2);
System.out.println("Total odd numbers are " + count / 2);
} else {
if (firstnum % 2 == 0) {
System.out.println("Total Even numbers are ");
System.out.println((count + 1) / 2);
System.out.println("Total Odd numbers are ");
System.out.println((count - 1) / 2);
} else {
System.out.println("Total even numbers are ");
System.out.println((count - 1) / 2);
System.out.println("Total odd numbers are ");
System.out.println((count + 1) / 2);
}
}
}
}

Adding constraints to integers

I am trying to limit the input number to be greater than 0 and an integer.
Code Here:
import java.util.Scanner;
public class PROB4_CHAL1 // Sum of Numbers
{
public static void main(String[] args)
{
int sum = 0;
int count = 1;
int number = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
while (number >= count)
{
sum += count;
count ++;
}
System.out.println("Sum equals " + sum);
}
}
New to Java so anything will help!
You can take the input in a while loop, like so:
int number = 0; // start at 0 so the while loop is true for the first time
while (number < 1) {
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
}
This way it will keep asking them to input a number until the number they input is greater than 0.

Categories

Resources