我正在創建一個程序,它將打印出用戶指定數字的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)。
。 – Mesop 2012-05-26 07:58:28