2012-04-28 166 views
0

我正在創建一個程序,它將打印出用戶指定數字的pi數字。我可以讀取來自用戶的輸入,我可以讀取文本文件,但是當我打印數字的位數時,它會打印出錯誤的數字。無法打印出讀取整數:java

「Pi.txt」包含「3.14159」。 這裏是我的代碼:

package pireturner; 

    import java.io.*; 
    import java.util.Scanner; 

    class PiReturner { 

     static File file = new File("Pi.txt"); 
     static int count = 0; 

     public PiReturner() { 

     } 
     public static void readFile() { 
      try { 
       System.out.print("Enter number of digits you wish to print: "); 
       Scanner scanner = new Scanner(System.in); 
       BufferedReader reader = new BufferedReader(new FileReader(file)); 
       int numdigits = Integer.parseInt(scanner.nextLine()); 

       int i; 
       while((i = reader.read()) != -1) { 
        while(count != numdigits) { 
         System.out.print(i); 
         count++; 
        } 
       } 

      } catch (FileNotFoundException f) { 
       System.err.print(f); 
      } catch (IOException e) { 
       System.err.print(e); 
      } 
     }    

     public static void main(String[] args) { 
      PiReturner.readFile(); 
     } 
    } 

這會打印出「515151」,如果作爲他們希望打印的位數用戶輸入3。我不知道它爲什麼這樣做,我不確定我做錯了什麼,因爲沒有錯誤,我已經測試了閱讀方法並且工作正常。任何幫助將很樂意欣賞。提前致謝。

順便說一下,將整數'i'轉換爲char將打印出333(假設輸入爲3)。

+0

。 – Mesop 2012-05-26 07:58:28

回答

0

你的內循環之前不輸出numdigit次3

  while (count != numdigits) { 
      System.out.print(i); 
      count++; 
     } 

,而不是離開......

int numdigits = Integer.parseInt (scanner.nextLine()); 
    // for the dot 
    if (numdigits > 1) 
     ++numdigits; 
    int i; 

    while ((i = reader.read()) != -1 && count != numdigits) { 
     System.out.print ((char) i); 
     count++; 
    } 
2

值51是字符'3'的Unicode代碼點(和ASCII值)。

要顯示3代替51你需要在打印之前將其int轉換爲char

System.out.print((char)i); 

你也有你的循環錯誤。你應該有一個循環,你如果不是你到達文件的末尾停止,或者如果你達到所要求的位數:

while(((i = reader.read()) != -1) && (count < numdigits)) { 

你的代碼也被視爲一個數字的字符.,但它是不是一個數字。

+0

謝謝,但打印出「333」。你知道這是爲什麼嗎? – 2012-04-28 09:36:53

+0

那太好了。我已經得到它與您的循環工作,我會簡單地添加「包括」3.「 「在問題中。今後我會研究如何消除'3'。 (除非你已經知道如何和謹慎地告訴)。非常感謝,這已經困擾了我很長一段時間。 – 2012-04-28 09:51:24

0

您只從文件'3'(字符代碼51,如Mark Byers指出)中讀取一個字符,然後將其打印3次。

 int i; 
    while((count < numdigits) && ((i = reader.read()) != -1)) { 
     System.out.print((char)i); 
     count++; 
    } 

如果用戶說,他們希望4位圓周率,你打算打印3.143.141

上面的代碼會打印3.14 4 - 因爲它是4個字符。如果你的問題解決了,你應該旗接受的答案