I’m trying to scann a String from the terminal and convert the second word into a double so I can use it inside a method which takes a double as an argument. So when I give accelerate 10 in the terminal, I can use accelerate to trigger a method called accelerate and give 10 as an argument to it. This is my code:
public static void main(String[] args) {
Racecar racecar = new Racecar();
Scanner scanner = new Scanner(System.in);
while (true) {
String scanned = scanner.nextLine();
if (scanned.split(" ")[0] == "accelerate") {
racecar.accelerate(scanned.split(" ")[1].Double.parseDouble());
}
}
}
This is the error I’m getting:
java: cannot find symbol
symbol: variable Double
location: class java.lang.String
>Solution :
2 issues here:
Double.parseDoubletake aStringas an argument, so what you want isDouble.parseDouble(scanned.split(" ")[1])instead ofscanned.split(" ")[1].Double.parseDouble()- Strings are not compared using
==but usingequals, so your code should be
this
if (scanned.split(" ")[0].equals("accelerate")) {
racecar.accelerate(Double.parseDouble(scanned.split(" ")[1]));
}
ideally, to avoid splitting twice, refactor the code like this:
String[] splitted = scanned.split(" ");
if (splitted[0].equals("accelerate")) {
racecar.accelerate(Double.parseDouble(splitted[1]));
}