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;
}
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);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With