我创建方法时,我的Java代码显示编译器错误

时间:2017-05-06 17:30:25

标签: java compiler-errors

package aj;

import java.util.Scanner;

public class ConvertingNumber {

    public static void main(String[] args) {

        Scanner a = new Scanner(System.in);
        System.out.println("Enter the Number");
        int num = a.nextInt();
        System.out.println("Enter the base for the given number");
        int base = a.nextInt();
        converting(num,base);

        public static int converting(int num , int base) {

            String sum="";

            while(num > 0) {
                int rem = 0;
                rem = num % base;
                num = num / base;
                sum = rem + sum;
            }

            System.out.println(sum);
        }   
    }
}

对于我上面的java代码,我得到更复杂的错误说:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The method converting(int, int) is undefined for the type ConvertingNumber
void is an invalid type for the variable converting
Syntax error on token "(", ; expected
Duplicate local variable num
Syntax error on token ",", ; expected
Duplicate local variable base
Syntax error on token ")", ; expected
at aj.ConvertingNumber.main(ConvertingNumber.java:12)

请有人帮我解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:3)

converting方法应该在主方法

之外
package aj;

import java.util.Scanner;

public class ConvertingNumber {
    public static void main(String[] args) {
        Scanner a=new Scanner(System.in);
        System.out.println("Enter  the Number");
        int num=a.nextInt();
        System.out.println("enter the base for the given number");
        int base=a.nextInt();
        converting(num,base);
    }

    //This method should be out side the main method
    public static void converting(int num , int base) {
        String sum="";
        while(num>0) {
            int rem=0;
            rem=num%base;
            num=num/base;
            sum=rem+sum;
        }
        System.out.println(sum);

    }   

}

答案 1 :(得分:0)

我已更正您的代码..

package aj;

import java.util.Scanner;

public class ConvertingNumber  {
public static void main(String[] args) {
    Scanner a=new Scanner(System.in);
    System.out.println("Enter  the Number");
    int num=a.nextInt();
    System.out.println("enter the base for the given number");
    int base=a.nextInt();
    ConvertingNumber .converting(num,base); 
           //converting(num,base);

}

    public static int converting(int num , int base)
    {
        int sum=0;
        while(num>0)
        {
            int rem=0;
            rem=num%base;
            num=num/base;
            sum=rem+sum;
        }
        //System.out.println(sum);
        return sum;
        } 

}