In: Computer Science
(JAVA)
Implementing a Program Design a program that prompts the
user for twenty numbers. If the number is positive, then add the
number to the current sum. If the number is negative, then subtract
the sum by one. Implement just the main method. Assume that all
libraries are imported, and class has been declared.
Java code:
import java.util.Scanner;
public class Main{
//required main function(from line 4 to 25) sample class is written
only to print the output
public static void main(String[] args){
Scanner input=new
Scanner(System.in);
//initializing number
int num,sum=0;
//asking for num
for(int i=0;i<20;i++){
//asking for number
System.out.print("Enter the number:
");
//accepting it
num=input.nextInt();
//checking if the number is
positive
if(num>=0)
//adding the number to sum
sum+=num;
else
//decrementing sum by 1
sum--;
}
//printing sum
System.out.println("Sum="+sum);
}
}
Screenshot:
Input and Output: