2014-07-07 155 views
0

我有一個簡單的問題,我不能看到,希望另一組眼睛可以幫助我。除了我認爲的filereader之外,一切都完美無缺。我應該讓用戶輸入把它放到一個文件中,讀取該文件並做出正確的操作。但由於某種原因,它只會對用戶輸入的最後一次輸入進行操作,並執行用戶想要運行該程序的次數。FileReader似乎不起作用

因此,例如,用戶將在3次,他想運行的提示,他進入344.34,5533.23,34.55,但它正確地保存到文件,但輸出文件

Thirty-four dollars and 55 cents 
Thirty-four dollars and 55 cents 
Thirty-four dollars and 55 cents 

我找不出爲什麼要這樣做。由於

public class Driver 
    { 
    public static void main(String[] args) throws IOException 
    {  
    // reads from keyboard 
    Scanner kb = new Scanner(System.in); 
    //writes to file 
    FileWriter fw =new FileWriter("input.txt"); 
    BufferedWriter bw = new BufferedWriter(fw); 

    double input; //variable to get users input 

    System.out.println("How many times do you want to convert? "); 
    int amount = kb.nextInt(); 
    //loop to go through users inputs and save to file 
    do 
    { 
     System.out.println("Enter currency to change to words: "); 
     while(!kb.hasNextDouble()) 
     { 
      System.out.println("Please enter a correct currency: "); 
      kb.next(); 
     } 

     input = kb.nextDouble(); 
     bw.write(String.valueOf(input)); 
     bw.newLine(); 
     amount--; 

    }while(amount > 0); 
    bw.close(); 

    Scanner read = new Scanner(new FileReader("C:\\Users\\Karmen\\workspace\\currencytoword\\input.txt")); 
    FileWriter fw2 =new FileWriter("output.txt"); 
    BufferedWriter bw2 = new BufferedWriter(fw2); 

    double input2; 

    // loop to go through the file read and get convert the curreny to words and save in a output file. 
    while(read.hasNext()) 
    { 
     input2 = read.nextDouble(); 
     int dollar = (int) input2; 
     int cents = (int)Math.round((input2 - dollar) * 100); 
     String word = numToWord(dollar); 
     if(word == "null") 
     { 
      bw2.write("Number too large"); 
     } 
     else 
      bw2.write(input + ": " + word + " dollars and " + cents + " cents"); 
      bw2.newLine(); 
    } 
    System.out.println("Program is done"); 
    bw2.close(); 
} 
+2

我無法重現您的問題。我能找到的唯一的錯誤是,當你編寫你的輸出文件時,你在每一行都預先輸入'input'而不是'input2'。當我運行你的程序時,'from'值是錯誤的,但是轉換後的值都是正確的。你確定你正在運行的代碼是你在這裏發佈的嗎?嘗試重新編譯並再次運行。 – azurefrog

回答

4

我想我找到了你的問題。它在這裏:

else 
     bw2.write(input + ": " + word + " dollars and " + cents + " cents"); 
     bw2.newLine(); 

你寫了input當你真的應該寫input2。 所以正確的代碼是:

else 
     bw2.write(input2 + ": " + word + " dollars and " + cents + " cents"); 
     bw2.newLine(); 

這說明了爲什麼你真的應該使用變量名是更具描述性的,而不是自相似;它有助於防止愚蠢的小錯誤。 (例如,在這裏,userInputfileInput會比inputinput2好得多)

+1

描述性變量名稱也使得調試更容易,因爲您可以更輕鬆地在調試器中查找所需的變量。 – Unihedron

+0

@azurefrog提到了這個問題。我只在冒號重複之前獲得該項目,實際轉換才能正確打印。 – River