我在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;
}
答案 0 :(得分:11)
只需创建一个Util
课程(例如:ConvertionUtil.java
),并将此方法作为static
方法放在那里。
public class ConvertionUtil{
public static int suit2Num(String t){
---
}
}
<强>用法:强>
int result = ConvertionUtil.suit2Num(someValidStirng);
答案 1 :(得分: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;
}
}
答案 2 :(得分: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();
}
}
}