java - 计数输出不正确

标签 java input output

我正在编写一个程序,该程序将继续接受数字,直到用户输入 -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);
}
}

最佳答案

问题出在你的最终值-1上。对于 -1,您的 sumOfDigits 函数也将返回 0。因此只有 count 总是增加 1。

while (run){
    System.out.println("Enter the number");
    n = sc.nextInt();
    if (n == -1){
        break; //Break if the end of input reached.
    }
    if (isDivisibleByNine(n)){
        count = count + 1;
    }

}

关于java - 计数输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994489/

相关文章:

python - 从 python 脚本调用 psexec 不会显示整个输出

architecture - cmake - 创建架构感知 makefile

java - [apache poi xssf] :creating pivot table in new sheet(Java)

c++ - 使用 cin,如何接受字符或整数作为输入?

javascript - 使用正则表达式和 jQuery 使输入接受一个字母

python - python 的 cocos2d 中的 raw_input() 等效项

java - 我收到此错误 : The markup in the document following the root element must be well-formed

java - 如何在不可编辑的 JTextField 中显示图像?

java - 使用注释和 lombok 的字段切入点

c++ - 输出函数 C++ 的问题