Handling Multiple Inputs in a Loop
Scorri per mostrare il menu
When building interactive Java programs, you often need to process several user inputs one after another. Instead of writing separate statements for each input, you can use a loop to repeatedly prompt the user. The while loop works especially well for this task because it allows your program to keep asking for input until a certain condition is met. By combining a while loop with the Scanner class, you can easily handle multiple user entries in a flexible way.
Main.java
12345678910111213141516171819202122232425package com.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter numbers (enter a negative number to stop):"); int number = 0; while (number >= 0) { System.out.print("Enter a number: "); number = scanner.nextInt(); if (number >= 0) { System.out.println("You entered: " + number); } else { System.out.println("Negative number detected. Exiting loop."); } } scanner.close(); } }
In this approach, the loop continues to prompt the user for input as long as the condition remains true—in this case, until the user enters a negative number. The termination condition is crucial: it determines when the loop should end. Providing clear feedback to the user, such as letting them know how to exit the loop or confirming their entries, helps make your program more user-friendly and prevents confusion during repeated input.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione