5

我在 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;   
}
4

3 回答 3

11

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

public class ConvertionUtil{

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

}

用法:

int result = ConvertionUtil.suit2Num(someValidStirng);
于 2013-10-11T11:22:09.790 回答
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;   
    }
}
于 2013-10-11T11:22:46.553 回答
0

我认为你应该使用这样的异常”

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) throws InvalidInputException{
        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: {
                throw new InvalidInputException();
            }
        }
        return n;   
    }
}

你可以只使用你需要的类的静态方法,如下所示:

package com.example;

import static MyClass;

public class MMMain{

public static void main(String[] args) {
        try {
            System.out.println(suit2Num("Cassandra"));
            System.out.println(suit2Num("Wrong line"));
        } catch(InvalidInputException e) {
            e.printStackTrace();
        }
    }
}
于 2013-10-11T11:42:08.230 回答