0

What is the output of this program if the input: 1 2 3 4 -5 0 26?

import java.util.Scanner; public class Q_09 { public static void main(String[] args) { int n, neg_count=0,sum=0; Scanner input=new Scanner(System.in); System.out.println("Enter n:"); n=input.nextlnt(); while(n !=0) { n=input.nextlnt(); if(n<0) neg_count++; sum +=n; System.out.println("sum="+sum); } System.out.println("#of negatives:"+ neg_count +"\t"+"Total="+sum); } }

21st Feb 2020, 1:45 AM
JOHANNA POLOABAD
JOHANNA POLOABAD - avatar
4 Respuestas
+ 1
'n' is not decremented inside the loop so the while will run infinite times.
21st Feb 2020, 1:57 AM
Avinesh
Avinesh - avatar
0
Code got syntax error. In `nextInt` you use lowercase 'L => 'l'', while you instead should use uppercase 'i' => 'I'. If you want the real sum you could add the first <n> into <sum>. In your code you only add the second and successive <n> into <sum>. I'm not even sure what you want by this code. You can opt to use do-while loop here, as you read <n> at least once. You can check value of <n> and exit loop by using `if` inside the do-while loop.
21st Feb 2020, 3:03 AM
Ipang
0
Ipang he is getting the number of integer inputs outside the loop and then taking that many inputs inside the loop and adding them. For the whole loop to successfully terminate, he should give the last input as 0. It needs some modifications in order to work properly.
21st Feb 2020, 3:43 AM
Avinesh
Avinesh - avatar
0
int count = input.nextInt(); while (count-- != 0) { n = input.nextInt();
21st Feb 2020, 5:51 AM
zemiak