I’m trying to write a method in java to run cases of a user-entered string.
The code:
static String checkWMI(String userVIN){
String manCountry = null;
String WMI = userVIN.substring(0, 5);
String Wcheck = WMI.substring(WMI.length()- 4);
if(Wcheck.equals("1") || Wcheck.equals("4") || Wcheck.equals("5")) {
manCountry = "United States";
}else if(Wcheck.equals("J")){
manCountry = "Japan";
}else if(Wcheck.equals("2")){
manCountry = "Canada";
}else if(Wcheck.equals("3")){
manCountry = "Mexico";
}else if(Wcheck.equals("S")){
manCountry = "United Kingdom";
}else if(Wcheck.equals("W")) {
manCountry = "Germany";
}
return manCountry;
}
}
The goal is to get a specific sub-string (so I can print it out later) and then determine a value based on a piece of that substring. I want to decide this based on the character indexed at zero. When I try to run this code, only "null" prints because it says my "if statement is always false". I know there must be a logic error somewhere, but I can’t find it. Any suggestions?
>Solution :
static String checkWMI(String userVIN){
String manCountry = null;
String WMI = userVIN.substring(0, 5);
if(WMI.startsWith("1") || WMI.startsWith("4") || WMI.startsWith("5") ) {
manCountry = "United States";
}else if(Wcheck.equals("J")){
manCountry = "Japan";
}else if(Wcheck.equals("2")){
manCountry = "Canada";
}else if(Wcheck.equals("3")){
manCountry = "Mexico";
}else if(Wcheck.equals("S")){
manCountry = "United Kingdom";
}else if(Wcheck.equals("W")) {
manCountry = "Germany";
}
return manCountry;
}
}
or
static String checkWMI(String userVIN){
String manCountry = null;
String WMI = userVIN.substring(0, 5);
if(WMI.charAt(0) == "1" || WMI.charAt(0) == "4" || WMI.charAt(0) == "5" ) {
manCountry = "United States";
}else if(Wcheck.equals("J")){
manCountry = "Japan";
}else if(Wcheck.equals("2")){
manCountry = "Canada";
}else if(Wcheck.equals("3")){
manCountry = "Mexico";
}else if(Wcheck.equals("S")){
manCountry = "United Kingdom";
}else if(Wcheck.equals("W")) {
manCountry = "Germany";
}
return manCountry;
}
}