5. 【问题描述】Fibonacci序列处理
从文件in.txt中读取第一个数作为Fibonacci数列的开始数n,读取第二个数,作为需要写入的数的个数m。###
将从n开始的m个Fibonacci数列写入到文件out.txt中。###
【输入形式】文件in.txt
【输出形式】文件out.txt
【样例输入】###
3 4
【样例输出】###
3 4 7 11
【样例说明】###
【评分标准】###
分析:个人认为此题有问题,没有给出第二个数,此题默认第二个数的值为第一个数加一##
package naizi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Fibonacci {
public static void rwFile(){
FileWriter fw = null;
BufferedReader br = null;
try {
File file = new File("out.txt");
if(file.exists()){
file.delete();
}
br = new BufferedReader(new InputStreamReader(new FileInputStream("in.txt")));
fw = new FileWriter("out.txt", true);
String line = null;
while ((line = br.readLine()) != null) {
int n1 = line.indexOf(" ");
String m1 = line.substring(0, n1);
int a = Integer.valueOf(m1);
int b=a+1;
String m2 = line.substring(n1+1,line.length());
int d = Integer.valueOf(m2);
int c = a + b;
String Fibo = m1+" "+String.valueOf(b);
for(int i=2;i<d;i++){
Fibo += " ";
Fibo += String.valueOf(c);
a=b;
b=c;
c=a+b;
}
fw.write(Fibo);
fw.flush();
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
rwFile();
}
}
运行结果如图:
1. in.txt
2. out.txt
3. 目录结构: