2012-04-28 84 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个字符。如果你的问题解决了,你应该旗接受的答案