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

Java如何打印1-10000间用户输入值的除数?代码问题求助

Fixing Your Divisor Printing Code

Let's sort out the two issues in your code step by step:

1. Identify the Key Problems

Your code has two main issues causing the incorrect output and syntax error:

  • Syntax Error: The line System.out.println("loop); is missing a closing double quote, and you're trying to print the string "loop" instead of the integer variable loop.
  • Logic Error: The print statement runs on every loop iteration, not just when loop is a valid divisor of your input number. That's why it's printing all numbers from 1 to your input value.

2. Corrected Working Code

Here's the fixed version that only prints divisors and resolves the syntax issue:

import java.util.Scanner;
public class Divisors {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;
        while(true) {
            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();
            if (Range < 1 || Range > 10000)
                System.out.println("Wrong choice");
            else break;
        }
        Divisor = 0; // Start counting Divisor from Zero
        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0) {
                Divisor++;
                System.out.println(loop); // Print only when it's a valid divisor
            }
        }
        System.out.println("Total number of divisors of " + Range + " is " + Divisor);
    }
}

3. What This Fixes

When you input 10 now:

  • It will print 1, 2, 5, 10 (only the valid divisors)
  • The final count will correctly show Total number of divisors of 10 is 4

A quick style tip: Java convention uses camelCase for variable names, so you might want to rename Range to range and Divisor to divisor for better readability — this doesn't affect functionality, just makes your code easier for other Java developers to follow.

内容的提问来源于stack exchange,提问作者Mohammed Hashim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:22:38