I’m currently making a small program to teach me some new Java, and I’m stuck. The program i’m making, you enter in a pre-set location and it will give you the jist of how far it is. Except I want to add in two+ word locations, except whenever I enter them in, it goes straight to the else statement, instead of giving the jist. My code is below.
import java.util.*;
public class Distance {
String _destination;
public Distance() {
Scanner scan = new Scanner(System.in);
System.out.println("Where do you want to go?");
_destination = scan.next();
if(getDistance() >= 2000) {
System.out.println("F*cking woop c*nt");
} else if(getDistance() >= 500) {
System.out.println("F*cking far c*nt");
} else if(getDistance() < 0) {
System.out.println("What are you? Retarded?");
} else if(getDistance().equals("0") {
System.out.println("Why bother?");
} else {
System.out.println("Walk it c*nt");
}
}
public int getDistance() {
int distance = 0;
if(_destination.equalsIgnoreCase("Ellenbrook")) {
distance = 1200;
} else if(_destination.equalsIgnoreCase("Midland")) {
distance = 900;
} else if(_destination.equalsIgnoreCase("Perth")) {
distance = 200;
} else if(_destination.equalsIgnoreCase("Woop Woop")) {
distance = 2100;
} else if(_destination.equalsIgnoreCase("High Wycombe")) {
distance = -2;
}
return distance;
}
public static void main(String[] args) {
new Distance();
}
}
Scanner tokenizes on the space character by default, so your call to next is only ever returning one word. You need to change your scanner to tokenize with newline, or use a BufferedReader (and the readLine method) to get your input instead.