2013-10-11 13 views
5

クラスオブジェクトを使用しないJavaで関数を定義しています。これは単にユーザーからの文字列入力を整数に変換するために使用されます。私がどこに関数を置いても、私はエラーを出します。私はどこに置くべきだろうと思っていた。そしてそこstatic方法として、この方法を置く:ここではそれはちょうど1つのUtilクラス(ConvertionUtil.java EX)を作成非クラスメソッドを定義する場所はどこですか?

//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; 
} 

答えて

11

です。

public class ConvertionUtil{ 

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

} 

用途:

int result = ConvertionUtil.suit2Num(someValidStirng); 
+0

注:「良い」静的メソッドは、渡された入力以外に参照すべきではありません。このようにして、コードのテスト能力には影響しません。 –

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; 
    } 
} 
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(); 
     } 
    } 
} 
関連する問題