Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to define non-class method?

Tags:

java

I am defining a function in Java that doesn't use class object. It is simply used to convert the string input from the user to an integer. No matter where I place the function I get and error. I was wondering where I should place it. Here it is

//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;   
}
like image 530
chikitin Avatar asked Oct 11 '13 11:10

chikitin


2 Answers

Just create one Util class(ex: ConvertionUtil.java) and put this method as a static method there.

public class ConvertionUtil{

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

}

Usage:

int result = ConvertionUtil.suit2Num(someValidStirng);
like image 138
Suresh Atta Avatar answered Sep 29 '22 09:09

Suresh Atta


You define it inside a class (everything is a class in Java), but make it 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;   
    }
}
like image 21
maksimov Avatar answered Sep 29 '22 07:09

maksimov