java - For loop printing an unexpected number of times -
public static void main (string[] args) { scanner input = new scanner(system.in); int[] array = new int[5]; system.out.print("please enter 5 numbers. \na="); array[0] = input.nextint(); system.out.print("\nb="); array[1] = input.nextint(); system.out.print("\nc="); array[2] = input.nextint(); system.out.print("\nd="); array[3] = input.nextint(); system.out.print("\ne="); array[4] = input.nextint(); boolean totaliszero = false; (int i=0;i<array.length ;i++) { (int j=1;i>j ;j++ ) { if ((array[i] + array[j])==0) { system.out.println("the numbers " + array[i] + " , " + array[j] + " have total sum equal 0."); totaliszero = true; } } } if (!totaliszero) { system.out.print("none of numbers have total sum of 0 each other. "); } }
here simple code wrote. task check if sum between every 2 numbers in array (consisting of 5 numbers) equal zero.
the problem have when there 2 pairs of numbers, both equal 0, @ end of program there message 1 of pairs only, not both, expected.
how can fix that, user can read there 2 pairs of numbers equal 0?
not sure if work because haven't tested , haven't used java in while, create array same way in post, try rest actual bulk of function.
// various input calls above^ create array int count = 0; for(int = 0; < array.length; i++) { for(int j = + 1; j < array.length; j++) { if(array[i] + array[j] == 0) { system.out.println("the numbers " + array[i] + " , " + array[j] + " have sum equal zero."); count++; } } } if(count == 0) { system.out.println("no sum between numbers equal 0"); }
Comments
Post a Comment