Java 使用方法将数字相加

Java 使用方法将数字相加,java,methods,Java,Methods,此代码旨在对数字的位数进行求和,但它会 javac Root.java Root.java:17: error: '.class' expected 谁能解释这里的问题是什么。另外,我想使用数组制作相同的程序,但我在数组中放入int时遇到问题,如果您有建议,我很乐意在这里告诉您 import java.util.Scanner; class Root { public static int numRoot(int n, int sum){ while (n != 0

此代码旨在对数字的位数进行求和,但它会

javac Root.java Root.java:17: error: '.class' expected
谁能解释这里的问题是什么。另外,我想使用数组制作相同的程序,但我在数组中放入int时遇到问题,如果您有建议,我很乐意在这里告诉您

import java.util.Scanner;

class Root {

    public static int numRoot(int n, int sum){
        while (n != 0) {
            sum = sum + n % 10; 
            n = n / 10;
        }
        return sum;
    }

    public static void main(String[] args){
        int sum = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number here");
        int n = in.nextInt(); 
        int root = numRoot(int sum, int n);
        System.out.print("the sum of the digits off given num is " + root);
    }
}

这里有错误,请更正

int root = numRoot(int sum, int n); // this is wrong
换成

int root = numRoot(n,sum); // should use correct order of input parameters

这应该是您的方法,您不需要传递总和:

   public static int numRoot(int n){
        int sum=0;
        while (n != 0) {
            sum += n % 10; 
            n = n / 10;
        }
        return sum;
    }
你应该这样称呼它:

int root = numRoot(n);

求和在你的函数中是什么意思?耶耶!非常感谢它纠正了错误,但是现在我在求和方面有问题,我会马上纠正,仍然不正确,你应该将它改为numRootn,sum真的有什么区别吗???哦,是的,现在真的很管用,你能解释一下吗pleas@user3791431看看你的方法,n应该是第一个参数,后面是sum,另一个方法总是返回0@user3791431现在,您可以看到您得到的值是正确的sum@MadProgrammer同意在他的程序中是0