将字符串转换为double?

时间:2013-11-25 17:45:56

标签: java

首先,感谢您花时间阅读我的问题。我有三个文件用于练习继承,但我有一个关于将字符串转换为双精度的问题。我已经阅读了双打API,并了解到parseDouble在转换方面是最简单的方法,但我不知道在哪里可以将parseDouble放在下面提供的代码中。

//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?: ");

2 个答案:

答案 0 :(得分:5)

如果您使用Scanner,则无需将字符串转换为双精度数:它有一个非常适合您的方法 - nextDouble()读取下一个双精度数并将其返回给您:

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
}

答案 1 :(得分:2)

我认为最简单的方法是使用nextDouble()类的Scanner方法:)所以,而不是做

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

你可以使用

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

并将其传递给您的Animal班级(请记住改变相关参数的类型)