2013-11-25 223 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 
} 
相關問題