【发布时间】:2014-11-18 12:34:06
【问题描述】:
我正在编写一个程序,该程序将继续接受数字,直到用户输入 -1。然后它将显示可被 9 整除的项目数;使用一个特殊的属性——能被 9 整除的数字的数字之和,它们本身也能被 9 整除。有人告诉我要依赖 高度模块化 方法。简单的输入,没有数组。
没有编译错误之类的东西,但是count的值总是错误的。比如我输入18,18,4,4,2,5,19,36,-1,预期的输出是3,但是输出出来了如 4. 我不知道为什么。我试过count++和++count,它们产生相同的输出。我哪里错了?
import java.util.Scanner;
public class Div{
static Scanner sc = new Scanner(System.in); boolean run = true; static int n = 0;
static int count = 0;
public static void main(String[] args){
Div a = new Div();
a.accept();
a.display();
}
void accept(){
while (run){
System.out.println("Enter the number");
n = sc.nextInt();
if (isDivisibleByNine(n)){
count = count + 1;
}
if (n == -1){
run = false;
}
}
}
static int sumOfDigits(int a){
int m = a; int sum = 0;
while (m>0){
sum = sum + (m%10); m /= 10;
}
return sum;
}
static boolean isDivisibleByNine(int x){
if (sumOfDigits(x)%9==0){
return true;
}
else {
return false;
}
}
void display(){
System.out.println("The total number of numbers that are divisible are: " + count);
}
}
【问题讨论】:
-
你试过输出那些被认为是可分的吗?然后您可以查看是哪一个导致了问题并从那里进行调试。
-
先尝试
if(n==-1),然后再尝试else if (isDivisibleByNine(n)) -
@CoolGuy,很棒的答案!编码差异如此之小,输出差异如此之大。极好!现在工作正常:)