Java中BigInteger的字符串[关闭]

问题描述 投票:1回答:1

这是我的代码:

public class sample {
   public static void main(String []args) throws Exception {

      System.out.println("Enter from file:");

      BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\KK\\A Key.txt"));

      String currentline;

      while((currentline=br.readLine())!=null){

         System.out.println(currentline);
      }

      BigInteger a = new BigInteger(currentline); 

      System.out.println(a);

  }

我想从文本文档中读取,从字符串转换为大整数,我试过这个但是我得到一个运行时错误,如何将String转换为相应的大整数Ascii值。

java string biginteger
1个回答
11
投票

你的问题非常简单:你从一个空字符串构建一个BigInteger!

您正在循环,直到currentLine为空。

然后你尝试从那里创建一个BigInteger!

只需将事物移入循环:

while((currentLine=br.readLine())!=null) {           
 System.out.println(currentLine);
 BigInteger a = new BigInteger(currentline); 
 System.out.println(a);
}

Etvoilà,事情正在发挥作用(假设您希望文件中的每一行都是一个数字)。如果整个文件代表一个数字,那么你必须按照zstring在他的注释中建议:你必须使用StringBuilder例如将所有行“收集”到一个字符串中,然后用它来创建BigInteger对象。

请注意java编码样式:类名称以大写字母开头;和变量名使用camelCase(因此我改为currentLine)。

但仅仅是为了记录:你写了一个低质量的问题。在询问“为什么我的代码不能正常工作”时,您应该始终包含编译器错误消息或堆栈跟踪。

© www.soinside.com 2019 - 2024. All rights reserved.