2013-11-25 82 views
1

首先,谢谢您花时间阅读我的问题。我有三个文件用于练习继承,但是我有一个关于将字符串转换为双精度的问题。我已经阅读了关于双打的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?: "); 
+0

有在你的代码中你无需*'parseDouble()'。如果你要添加一个计算长度或重量的方法,你可以在那里使用它。 – jonhopkins

回答

2

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

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类(记住要改变相关参数的类型)

+0

谢谢!我早些时候尝试过,并且在编译时遇到不兼容的类型错误。编辑:啊!我没有用双头来试试它:|。 Java错误总是最简单的事情。 – Monteezy

+1

好吧,你的长度变量是字符串,所以你需要改变这个倍数,你也需要改变你的动物和狗类的相关数据类型:) – JustDanyul

+0

改变我们交谈。很快会标记为答案。 – Monteezy

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 
}