java - check a list how many is positive number -
write programme called positivenegative reads unspecified number of integers, determines how many positive , negative values have been entered, , computes sum , average of input values (not counting zeros). reading of input ends when user enters 0 (zero). display number of positive , negative inputs, sum , average. average should computed floating-point number. design programme such asks user if want go on new inputs after each set of entries, ending programme when not respond question "yes".
here sample run:
input list of integers (end 0): 1 2 -1 3 0 # of positive inputs: 3 # of negative inputs: 1 total: 5.0 average: 1.25 go on new inputs? yes input list of integers (end 0): 0 no numbers entered except 0 go on new inputs? no
and here code:
import java.util.*; public class positivenegative { public static void main(string[] args){ scanner input = new scanner(system.in); string answer; int countpositive = 0; int countnegative = 0; int total = 0; int num = 0; system.out.print("input list of integers (end 0): "); do{ string list = input.nextline(); for(int = 0; ; i=i+2 ){ num = integer.parseint(list.substring(i,i+1)); if( num == 0) break; else if ( num > 0) countpositive++; else if ( num < 0) countnegative--; total = total + num; } double average = total/(countpositive + countnegative); system.out.println("# of positive inputs: "+countpositive); system.out.println("# of negative inputs: "+countnegative); system.out.println("the total: "+total); system.out.println("the average"+average); system.out.println("\n "); system.out.print("would go on new inputs? "); reply = input.next(); }while(answer.equalsignorecase("yes")); } }
i can compile file, when run it, can't result sample run.
you decrementing (countnegative--;
) count of negative integers instead of incrementing (countnegative++;
) when negative integer encountered.
java string loops
No comments:
Post a Comment