Issue
import java.util.Scanner;
public class SumAverage2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("average program");
System.out.println("Enter multiple integers greater than or equal to 0.");
System.out.println("Enter a negative integer to finish the entry.");
boolean end = false;
int n;
int sum = 0;
int count = 0;
while(!end) {
n = input.nextInt();
if (n>=0) {
sum = sum + n;
count++;
}else
end = true;
}
double average ;
average = (double) sum / (double) count ;
System.out.println("Number of integers greater than 0 entered = " + count);
System.out.println("sum of integers = " + sum);
System.out.printf("average = %.2f", + average);
input.close();
}
}
I'm trying to solve this problem, but the answer I want doesn't come out under certain conditions.
If I enter
3 7 1 -1
average program
Enter multiple integers greater than or equal to 0.
Enter a negative integer to finish the entry.
Number of integers greater than 0 entered = 3
sum of integers = 11
average = 3.67
// I made a program that comes out with this answer.
However, the condition "Do not output the sum and average if the user inputs a negative integer from the beginning" must be satisfied, but the code above does not work.
If I enter -10
average program
Enter multiple integers greater than or equal to 0.
Enter a negative integer to finish the entry.
Number of integers greater than 0 entered = 0
sum of integers = 0 average = NaN
// The answer comes as above.
The answer i want is //
average program
Enter multiple integers greater than or equal to 0.
Enter a negative integer to finish the entry.
Number of integers greater than 0 entered = 0 //
I've only been learning to code for 2 weeks, so I'm having a lot of difficulties. I'd be very grateful if you guys could help me.
Wrong answer press -10 //
average program
Enter multiple integers greater than or equal to 0.
Enter a negative integer to finish the entry.
Number of integers greater than 0 entered = 0
sum of integers = 0
average = NaN
Correct answer press -10 //
average program
Enter multiple integers greater than or equal to 0.
Enter a negative integer to finish the entry.
Number of integers greater than 0 entered = 0
I want to solve a problem that does not work under certain conditions.
Solution
Your count
is the number of numbers entered.
Wrap all the 'printing sum and average' stuff in 'if count > 0'.
System.out.println("Number of integers greater than 0 entered = " + count);
if (count > 0) {
double average = (double) sum / (double) count;
System.out.println("sum of integers = " + sum);
System.out.printf("average = %.2f", + average);
}
Answered By - Arfur Narf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.