Reputation: 27
When you enter either NY or NYC, the code still displays the error. I believe this has something to do with how I used the substring method but I can't figure it out for the life of me, any help appreciated.
import java.util.Scanner;
public class Practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter valid city initials: ");
String city = input.next();
while (city.substring(0,1)!= ("NY") && (city.substring(0,2)!= ("NYC"))){
System.out.println("Wrong City");
System.out.println("Enter New York Citys Initials: ");
city = input.next();
}
}
}
Upvotes: 0
Views: 541
Reputation: 33
The substring(int startIndex, int endIndex) method returns part of a string starting from the startIndex (inclusive) and ends at the endIndex (exclusive). Meaning
city.substring(0, 1)
only obtains the first character of the string.
Also, you should be using the string.equals(Object other) method to compare strings, not the '==' operator. The '==' operator will check if the references to the objects are equal, whereas equals() will check the data of the string. For example, you can check if the entire string is equal to something by doing:
if (city.equals("NYC")) {
//Do something
}
Edit: I also see that you're trying to get the third character of a string. If you try to type something with 2 (or less) characters that isn't "NY" exactly, it will return a StringIndexOutOfBoundsException, so you should also check the length of the input and apply appropriate actions.
Upvotes: 1
Reputation: 23
I think the problem lies with fact that for the input NYC the lines:
city.substring(0,1) //will return N
and the line
city.substring(0,2) //will return NY
Upvotes: 0