Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a word of a scanned String into a double in Java?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

2 issues here:

  1. Double.parseDouble take a String as an argument, so what you want is Double.parseDouble(scanned.split(" ")[1]) instead of scanned.split(" ")[1].Double.parseDouble()
  2. Strings are not compared using == but using equals, 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]));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading