I have a problem, when I use if statement in while loop, it works with if, but it doesn’t in else if
I need from program to print the largest number and the second largest number
here is the code
int num = S.nextInt(); int max = num; int max2 = num; while (num != -1) { if (num > max) max = num; else if (max2 <= num && max > num) max2 = num; num = S.nextInt(); } System.out.println("The max = " + max); System.out.print("The max 2 = " + max2 );
Advertisement
Answer
it’s not the problem why not go into else if.it’s logic problem.
I can show you example
int num = S.nextInt(); int max = num; int max2 = 0; while (num != -1) { if (num > max){ max2 = max; max = num; }else if (num > max2){ max2 = num; } num = S.nextInt(); } System.out.println("The max = " + max); System.out.print("The max 2 = " + max2 );
the solution is
- if max find bigger number.then give original max number to max2.and the new number to max
- in case the first num is the biggest.so we set max2 to 0.and if there is no bigger number than max,we do compare on max2