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 variableloop. - Logic Error: The print statement runs on every loop iteration, not just when
loopis 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
相关产品推荐
相关产品推荐

