java adding program: two consecutive zeroes would cause the total of all the values input to be printed and the program to be terminated -
i want make program work on 0-0 case. when input 0,it show subtotal 0 first, , need input 0 display total 0, in program, when input 0, show total 0.(a 0 value cause subtotal printed , reset zero)
class adding{ public static void main(string[] args){ scanner input = new scanner(system.in); int subtotal = 0; int total = 0; while(true){ while(true){ int number = input.nextint(); if(number == 0)break; subtotal = subtotal + number; } total = total + subtotal; if(subtotal != 0){ system.out.println("subtotal: " + subtotal); subtotal = 0; }else{ system.out.println("total: " + total); break; } } } }
it happening because of condition subtotal!=0. when enter 0 first input, subtotal 0. skip printing subtotal:0 , directly prints total:0. keep track or number of inputs have read. if subtotal!=0 or if first input, print subtotal.
so have added numbersread keep track of number of characters read. (you can simple boolean).
change code this:
class adding{ public static void main(string[] args){ scanner input = new scanner(system.in); int subtotal = 0; int total = 0; int numbersread=0; while(true){ while(true){ int number = input.nextint(); numbersread++; if(number == 0)break; subtotal = subtotal + number; } total = total + subtotal; if(subtotal != 0 || numbersread == 1){ system.out.println("subtotal: " + subtotal); subtotal = 0; }else{ system.out.println("total: " + total); break; } } } }
Comments
Post a Comment