我可以将文本文件中的数字相乘吗?

时间:2017-05-16 00:35:18

标签: text java.util.scanner bufferedreader

我有一个看起来像这样的文本文件 1 2 3 4
5 6 7 8
有没有办法可以将所有这些数字一起乘以?或者我是否必须将它们全部移到不同的线上?我知道BufferedReader和Scanner的基础知识,但我不确定这是否可行。我想要做的是将我从在线下载的素数列表相乘。这是我现在拥有的(更新的)

import java.io.*;    
public class BufferReader {   
public static void main(String[] args) {

   String delete = "[ ]+";
   BufferedReader br = null;

   try{ 
       br = new BufferedReader(new FileReader("test.txt"));     

       System.out.println("Reading the file using readLine() method:");
   String contentLine = br.readLine();
   while (contentLine != null) {
      System.out.println(contentLine);
      contentLine = br.readLine();
      String show [] = contentLine.split(delete);
   }



   } 
   catch (IOException ioe) 
   {
   ioe.printStackTrace();
   } 
   finally 
   {
   try {
      if (br != null)
     br.close();

   } 
   catch (IOException ioe) 
       {
    System.out.println("Error in closing the BufferedReader");
   }
}
 }
}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。

package eu.webfarmr;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class NumberReader {
    public static void main(String[] args) throws Exception {
        // 1. Determine the input location
        FileInputStream fis = new FileInputStream("c:/temp/file.txt");

        // 2. Read the contents of the file into a single string
        byte[] contentBytes = new byte[255];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (fis.read(contentBytes)!=-1){
            bos.write(contentBytes);
        }
        fis.close();
        String contents = bos.toString();
        System.out.println(contents);

        // 3. Parse the string and split according to the system's endline
        String[] lines = contents.split(System.getProperty("line.separator"));
        int product = 1;
        for (String line : lines){
            String[] numbers = line.trim().split(" ");
            for (String number : numbers){
                System.out.println("number read: "+number);
                Integer convertedNumber = Integer.parseInt(number.trim());
                product = product * convertedNumber;
                System.out.println("new product: "+product);
            }
        }

    }
}

我在您的输入上运行了代码并获得了:

1 2 3 4
5 6 7 8
number read: 1
new product: 1
number read: 2
new product: 2
number read: 3
new product: 6
number read: 4
new product: 24
number read: 5
new product: 120
number read: 6
new product: 720
number read: 7
new product: 5040
number read: 8
new product: 40320