2014-01-28 24 views
0

Java初學者在這裏,但我真誠地嘗試。這個程序的目標是從Realtor11.txt文件讀取兩個值並將它們分配給變量。閱讀文本文件併爲變量賦值

Realtor11.txt的內容是(無空格):

約翰

見部分//讀取Realtor11.txt不知道我在做什麼錯,但現在的錯誤是

Realtor11.java:48:錯誤:不兼容的類型 price = in.readLine(); ^ 要求:雙 發現:字符串 1錯誤 錯誤:無法找到或加載主類Realtor11 [完成了1.1s]

// java class for keyboard I/O 
import java.util.Scanner; 
// java class for JOption GUI 
import javax.swing.JOptionPane; 
// File reader 
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.InputStream; 

public class Realtor11 
{ 
    public static void main(String[] args) 
    { 
    // Keyboard and file input 
     Scanner console = new Scanner(System.in); 
     Scanner inputStream = null; 
    // price of the house, the cost to sell the house and the commission 
     double price, cost, commission; 
    // seller’s name 
     String seller; 

    // GUI diplay message declaration 
     String display_message = "This program calculates the cost to sell a home\n" 
     + "and the commission paid to an individual sales agent.\n\n" 
     + "The user is asked for the last name of the seller and the\n" 
     + "sales price.\n\n"; 

    // Output descriptive messages 
     JOptionPane.showMessageDialog(null, display_message, "Lab 1 Description", JOptionPane.INFORMATION_MESSAGE); 

    // Read Realtor11.txt 
     try { 
      BufferedReader in = new BufferedReader(new FileReader("Realtor11.txt")); 
      while (in.read()!= -1); 
      seller = in.readLine(); 
      price = in.readLine(); 
      in.close(); 
      } 
      catch (IOException e) {} 

    // calculate the cost and the commission 
     cost = 0.06 * price; 
     commission = 0.015 * price; 
    // display the input and results 
     String 
      out1 = String.format("%nThe " + seller + "’s" + " home sold for $%.2f%n", price), 
      out2 = String.format("The cost to sell the home was $%.2f%n", cost), 
      out3 = String.format("The selling or listing agent earned $%.2f%n", commission); 

     JOptionPane.showMessageDialog(null, out1 + out2 + out3, seller + "'s Home Sale", JOptionPane.INFORMATION_MESSAGE); 

    // Output to file 
    // still writing this. 

    } 
} 

回答

5

readLine()返回String值你希望哪裏的方法一個double值(see API)。您必須將String值轉換爲double像這樣:

price = Double.parseDouble(in.readLine()); 
+0

謝謝!我不知道我能做到這一點。我閱讀了Oracle文檔,沒有找到這種語法。 –

+0

沒問題。只要記住你必須在需要時進行轉換。另外,如果您發現此答案是正確的,請將其標記爲正確:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

0

readline的()函數返回一個字符串。您需要做的是手動將該價格字符串轉換爲雙倍價格 double price = Double.parseDouble(字符串版本的價格);