我正在创建一个程序,它将打印出 pi 的数字,最多可达用户指定的数字。我可以读取用户的输入,可以读取文本文件,但是当我打印位数时,它打印出错误的数字。
“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();
}
}
如果用户输入 3 作为他们想要打印的位数,这将打印出“515151”。我不知道它为什么这样做,我也不知道我做错了什么,因为没有错误,而且我已经测试了阅读方法,它工作正常。任何帮助将不胜感激。提前致谢。
顺便说一句,将整数“i”转换为字符将打印出 333(假设输入为 3)。
最佳答案
值 51 是字符 '3'
的 Unicode 代码点(和 ASCII 值)。
要显示 3
而不是 51
,您需要在打印之前将 int
转换为 char
:
System.out.print((char)i);
您的循环中也有错误。您应该有一个循环,如果到达文件末尾或达到所需的位数,则停止:
while(((i = reader.read()) != -1) && (count < numdigits)) {
您的代码还将字符 .
计为数字,但它不是数字。
关于java - 无法打印读取的整数: java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10362291/