我想也許這就是你追求的?主代碼遍歷所有字符串,然後依次在該字符串上運行每個可能的「檢查」。 「檢查」代碼本身存儲在一個數組中,該數組包含一個單一檢查(字符串)方法的對象,該方法被內聯覆蓋。你可以用一個check()方法來做你需要的任何事情,只要它是從標準簽名開始的,所以如果你需要正則表達式檢查或者更復雜的事情,那麼它也可以正常工作。
public class TestTypes
{
public static void main(String[] args)
{
String[] strings = new String[] {"123", "9999999999999", "50.4", "not a number"};
for(String str : strings)
{
System.out.print("'" + str + "': ");
for(TypeChecker checker : typesToCheck)
{
if(checker.check(str))
{
System.out.print(checker.type.getSimpleName() + " ");
}
}
System.out.println();
}
}
static abstract class TypeChecker
{
public final Class type;
public abstract boolean check(String s);
TypeChecker(Class type)
{
this.type = type;
}
}
// A list of the code for all the checks
static TypeChecker[] typesToCheck =
{
new TypeChecker(Integer.TYPE) // is Integer
{
public boolean check(String s)
{
try{Integer.parseInt(s);}
catch(Exception e)
{return false;}
return true;
}
},
new TypeChecker(Long.TYPE) // is Long
{
public boolean check(String s)
{
try{Long.parseLong(s);}
catch(Exception e)
{return false;}
return true;
}
},
new TypeChecker(Double.TYPE) // is Double
{
public boolean check(String s)
{
try{Double.parseDouble(s);}
catch(Exception e)
{return false;}
return true;
}
},
};
}
這將產生輸出:
'123': int long double
'9999999999999': long double
'50.4': double
'not a number':
該解決方案是很多更詳細,並具有間接擁有使其混亂的潛在水平,因此,如果你只是完成只有少數幾種可能的類型,我只是將其中的很多內容聯繫在一起,併爲每個人節省了麻煩!
如果您有複雜的算法需要在測試中運行,或者您需要能夠自定義在運行時動態執行哪些測試,那麼這種方法只是一種很好的方法。
什麼錯誤,,, ?? – 2012-02-29 10:16:02
你是什麼意思「檢查他們每個人,如果他們匹配指定的類型」? – 2012-02-29 10:17:35
你可能不應該用你的方式使用'switch'。 – beerbajay 2012-02-29 10:19:12