Monteezy
Monteezy

Reputation: 57

Converting string to double?

First off, thank you for taking time to read my question. I have three files that I am using to practice inheritance, however I have a question about converting strings to doubles. I have read the API on doubles and have an understanding that parseDouble would be the simplest way to go in terms of converting, but I am not sure where I can place parseDouble in the code provided below.

//Code Omitted
public Animal()
{
  name = "";
  weight = "";
  length = "";
  color = "";
}

public Animal(String n, String w, String l, String c)
{
  name = n;
  weight = w;
  length = l;
  color = c;
}

//Code Omitted The below class is an extension of my Animal class

public Dog()
{
  super();
  breed = "";
  sound = "";
}

public Dog(String n, String w, String l, String c, String b, String s)
{
  super(n,w,l,c);
  name = n;
  weight = w;
  length = l;
  color = c;
  breed = b;
  sound = s;
}

public String getName()
{
  return name;
}

public String getWeight()
{
  return weight;
}

public String getLength()
{
  return length;
}

public String getColor()
{
  return color;
}

public String getBreed()
{
  return breed;
}

public String getSound()
{
  return sound;
}

//Code Omitted
public static void main(String [] args)
{
  String name, weight, breed, length, sound, color;
  Scanner input = new Scanner(System.in);
  System.out.print("Please name your dog: ");
  name = input.next();
  System.out.print("What color is your dog? (One color only): ");
  color = input.next();
  System.out.print("What breed is your dog? (One breed only): ");
  breed = input.next();
  System.out.print("What sound does your dog make?: ");
  sound = input.next();
  System.out.print("What is the length of your dog?: ");
  length = input.next();
  System.out.print("How much does your dog weigh?: ");

Upvotes: 1

Views: 176

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You do not need to convert strings to doubles if you are using a Scanner: it has a method that is perfect for your purposes - nextDouble() reads the next double, and returns it back to you:

System.out.print("How much does your dog weigh?: ");
if (input.hasNextDouble()) { // Add a safety check here...
    weight = input.nextDouble();
} else {
    // User did not enter a double - report an error
}

Upvotes: 5

JustDanyul
JustDanyul

Reputation: 14054

I think the simplest way would be to use the nextDouble() method of the Scanner class :) So, instead of doing

System.out.print("What is the length of your dog?: ");
length = input.next();

you could use

System.out.print("What is the length of your dog?: ");
double length = input.nextDouble();

and pass that to your Animal class (remember to change the type of the relevant parameter though)

Upvotes: 2

Related Questions