Consider this Java code snippet that uses a while loop The i

Consider this Java 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.

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 + \"\ \");

}

}

Questions: 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)?

Could you rewrite this using another loop structure and if so how?

Solution

Hi,

I have fixed the issue and highlighted the code changes below.


import java.util.Scanner;

public class Test {
   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++;
   }
   System.out.print(\"You have entered a total of \" + numbersEntered + \"\ \");

  
   }
}

Using another loop with same program: Using for loop


import java.util.Scanner;

public class Test {
   public static void main(String[] args) { Scanner input = new Scanner(System.in);
   int numbersEntered = 0;
   int number;
   for(numbersEntered=0; numbersEntered < 10; numbersEntered++){
   System.out.println(\"Please enter a number\");
   number = input.nextInt();
   }
   System.out.print(\"You have entered a total of \" + numbersEntered + \"\ \");
  
   }
}

Output:

Please enter a number
1
Please enter a number
2
Please enter a number
3
Please enter a number
4
Please enter a number
5
Please enter a number
6
Please enter a number
7
Please enter a number
8
Please enter a number
9
Please enter a number
10
You have entered a total of 10

Consider this Java 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. public static vo
Consider this Java 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. public static vo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site