Write a Java program that will input integer values from the user. The user will enter a sequence of integer values in a loop that will go for maximum 10 iterations (declare a class constant for 10) but it will stop if the user is entering a negative value. The program computes the sum and the average of all positive numbers in the sequence.
HINT: You will need to implement a loop that is both count-controlled (has up to 10 iterations) and event-controlled (stops earlier if a negative value is entered).
OUTPUT (3 SAMPLES):
SAMPLE #1
Enter a number, negative to STOP: 1
Enter a number, negative to STOP: 2
Enter a number, negative to STOP: 3
Enter a number, negative to STOP: 4
Enter a number, negative to STOP: 5
Enter a number, negative to STOP: 6
Enter a number, negative to STOP: -8
===============================
You entered 6 positive numbers.
The sum = 21
The average = 3.50
SAMPLE #2
Enter a number, negative to STOP: -1
ERROR! Division by 0. No input.
SAMPLE #3
Enter a number, negative to STOP: 1
Enter a number, negative to STOP: 2
Enter a number, negative to STOP: 3
Enter a number, negative to STOP: 4
Enter a number, negative to STOP: 5
Enter a number, negative to STOP: 6
Enter a number, negative to STOP: 7
Enter a number, negative to STOP: 8
Enter a number, negative to STOP: 9
Enter a number, negative to STOP: 10
================================
You entered 10 positive numbers.
The sum = 55
The average = 5.50
my code is taking input an 11th time but not calculating it when i run it all the way through without entering a negative number. I want it to take input only 10 times and calculate sum for the 10 integers. Any help is greatly appreciated.
My Code:
import java.util.Scanner;
public class Assignment2_3 {
public static final int DONE = 10;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
int x;
int i = 0;
int sum = 0;
double avg;
System.out.print("Enter number, negative to STOP:");
n = input.nextInt();
if(n<0){
System.out.println("ERROR! Division by 0. No input.");
}
else{
for(x =1; x <DONE; x++){
if
(n>=0){
sum= sum + n;
System.out.print("Enter number, negative to STOP:");
n = input.nextInt();
}
}
avg = (double)sum/x;
System.out.println("===================================");
System.out.println("You entered " + x + " Positive integers");
System.out.println("The sum = " + sum);
System.out.printf("The average = %3.2f\n", avg);
}
}
}
This post has been edited by pmpinaintez11: 20 March 2009 - 07:24 PM

New Topic/Question
Reply




MultiQuote






|