Handling Multiple Inputs in a Loop
Sveip for å vise menyen
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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår