You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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 if statements and original limited while loop with a single if-else block. This properly handles both positive and non-positive inputs every time.
  • Removed Unnecessary Breaks: The original break statements 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:39:05