如何修改Java程序以实现重复计算正数平方根的循环逻辑
Fixing the Loop Logic for Continuous Input Handling
Got it, let's adjust your Java program so it runs continuously, letting you input multiple numbers without restarting. Here's the modified code with key improvements:
package com.mycompany.rooter; import java.util.Scanner; public class Rooter { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Infinite loop to keep accepting inputs until program is stopped while (true) { int userNum = 0; System.out.println("Please enter positive number: "); userNum = myObj.nextInt(); if (userNum > 0) { // Calculate and print square root for positive numbers System.out.println(Math.sqrt(userNum)); System.out.println("You successfully calculated the square root of a positive integer!!! Congratulations user. Try again for more."); } else { // Handle non-positive inputs System.out.println("You entered an integer less than or equal to Zero. Please try again with a positive number."); } // No break here—loop will automatically repeat for next input } } }
Key Changes Explained:
- Infinite Loop: The
while(true)loop ensures the program keeps running indefinitely (you can stop it by pressing Ctrl+C in the console). - Input Inside Loop: We moved the input prompt and
nextInt()call inside the loop, so a new number is requested every iteration. - Simplified Condition Checks: Replaced the nested
ifstatements and original limitedwhileloop with a singleif-elseblock. This properly handles both positive and non-positive inputs every time. - Removed Unnecessary Breaks: The original
breakstatements were causing the loop to exit after one input. Now, the loop repeats automatically after each input, whether it's valid or not.
This way, you can enter as many numbers as you want—positive numbers get their square roots calculated, non-positive numbers trigger an error message, and the program immediately prompts for another input without needing to restart.
内容的提问来源于stack exchange,提问作者Kyle Schaeffer
相关产品推荐
相关产品推荐

