Consider this code snippet that uses a while loop The intent

Consider this code snippet that uses a “while” loop. The intent of the program is to ask the user to enter 10 numbers and only 10 numbers. What is wrong with the code and how would you fix it? How would you test your fix to verify that you fixed the problem(s)?

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int numbersEntered = 0;
int number;
while (numbersEntered < 10) {
System.out.println(\"Please enter a number\");
number = input.nextInt();
System.out.print(\"You have entered a total of \" + numbersEntered + \"\ \");

}

}

Could you rewrite this using another loop structure and if so how? Your initial post should be a maximum of one paragraphs and should explain any errors with the code and how would fix them. Your initial post should describe how you would test your fix to verify that you fixed the problem(s).

Solution

Correct Code:

import java.util.*;
public class NumberCount
{
   public static void main(String[] args) {

   Scanner input = new Scanner(System.in);
   int numbersEntered = 0;
   int number;
   while (numbersEntered < 10) {
   System.out.println(\"Please enter a number\");
   number = input.nextInt();
   numbersEntered++; // increase the numbersEntered
   System.out.print(\"You have entered a total of \" + numbersEntered + \"\ \");
     
   }
   }
}

you need to do a increament to numbersEntered by 1 otherwise it will be a infinite loop.

Code using for loop:

import java.util.*;
public class NumberCount
{
   public static void main(String[] args) {

   Scanner input = new Scanner(System.in);
   int number;
   for(int numbersEntered=1;numbersEntered<=10;numbersEntered++) {
   System.out.println(\"Please enter a number\");
   number = input.nextInt();
   System.out.print(\"You have entered a total of \" + numbersEntered + \"\ \");
     
   }
   }
}

Consider this code snippet that uses a “while” loop. The intent of the program is to ask the user to enter 10 numbers and only 10 numbers. What is wrong with th
Consider this code snippet that uses a “while” loop. The intent of the program is to ask the user to enter 10 numbers and only 10 numbers. What is wrong with th

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site