11.9k views
0 votes
What is one potential problem with the following loop? System.out.print("Enter integers. Enter -1 to exit."); System.out.println(" Count of integers entered will be returned."); int n=0; int c=0; while (n != -1) { n = scan.nextInt(); c++; } System.out.println(c);

1 Answer

3 votes

Answer:

The answer to this question can be given as

The potential problem with the loop is it's counts when the user enters -1 from the keyboard, so the count will too many.

Explanation:

In the program there some line is missing. So the right program of the question can be given as:

import java.util.*; //import package for take input from user.

public class Main //define main class.

{

public static void main(String[] args)//define main function

{

Scanner scan=new Scanner(System.in); //creating object.

//print values.

System.out.print("Enter integers. Enter -1 to exit.");

System.out.println(" Count of integers entered will be returned.");

int n=0,c=0; //declaring integer variable.

while (n != -1) //loop

{

n = scan.nextInt(); //take input by user and hold on variable n.

c++;

}

System.out.println(c); //print value.

}

}

output:

Enter integers. Enter -1 to exit. Count of integers entered will be returned.

-1

1

User Helmut Kemper
by
5.5k points