在哪里定义非类方法?

chi*_*tin 5 java

我在Java中定义了一个不使用类对象的函数.它仅用于将用户的字符串输入转换为整数.无论我在哪里放置我得到的功能和错误.我想知道我应该放在哪里.这里是

//Basically, when the user enters character C, the program stores
// it as integer 0 and so on.

public int suit2Num(String t){
   int n=0;
   char s= t.charAt(0);
   switch(s){
   case 'C' :{ n=0; break;}
   case 'D': {n=1;break;}
   case 'H':{ n=2;break;}
   case 'S': {n=3;break;}
   default: {System.out.println(" Invalid suit letter; type the correct one. ");
            break;}
   }
return n;   
}
Run Code Online (Sandbox Code Playgroud)

Sur*_*tta 11

只需创建一个Util类(例如:) ConvertionUtil.java并将此方法作为static方法.

public class ConvertionUtil{

public static int suit2Num(String t){
    ---
}

}
Run Code Online (Sandbox Code Playgroud)

用法:

int result = ConvertionUtil.suit2Num(someValidStirng);
Run Code Online (Sandbox Code Playgroud)


mak*_*mov 8

你在一个类中定义它(所有东西都是Java中的一个类),但是要做到static:

public class MyClass {

    //Basically, when the user enters character C, the program stores
    // it as integer 0 and so on.
    public static int suit2Num(String t){
        int n=0;
        char s= t.charAt(0);
        switch(s) {
            case 'C' :{ n=0; break;}
            case 'D': {n=1;break;}
            case 'H':{ n=2;break;}
            case 'S': {n=3;break;}
            default: {
                System.out.println(" Invalid suit letter; type the correct one. ");
                break;
            }
        }
        return n;   
    }
}
Run Code Online (Sandbox Code Playgroud)