好的,我正在尝试使输出看起来有些特定。在新行上打印10个数字。出于某种原因,在循环4中运行后,它将i设置为0。我将从第一位开始读取文件。我最终希望将其写入新文件。这是一堂课,只有一个作业,我不是要你们做作业。 (基本上,我必须读取文件并使用第一个文件中指定的名称写入新文件。并且只能使用第一个文件顶部的数字。
txt文件内容:
MyOutput.txt 23
20 1 4 5 7
45
1 2 3 4 5 6 7 8 9 77 88 99 23 34
56 66 77 88 99 100 110 120
和代码 ...
package reading_with_exceptions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class inputFilename {
static Scanner kbInput = new Scanner(System.in);
public static void main(String[] args) {
String lines = null;
Scanner inFile = null;
int count = 0;
boolean metCount = false;
// TODO Auto-generated method stub
try {
inFile = new Scanner(new FileReader("src/MyInput.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lines = inFile.nextLine();
lines.trim();
//Now check to see if line is empty
//If not empty get the ouput file name and number of lines from file
if(lines.length()>0) {
String outPutFile = lines.substring(0, lines.indexOf(' '));
String numNumbers = lines.substring((lines.indexOf(' ')+1), (lines.length()-1));
numNumbers.trim();
count = Integer.parseInt(numNumbers);
System.out.print(outPutFile+" ");
System.out.println(count);
}
//
//check if there is another line in the file
int i=0;
while(inFile.hasNextLine() && !metCount) {
lines = inFile.nextLine();
String[] separated = lines.split(" ");
for( i = 0; i<separated.length; i++) {
System.out.print(separated[i]+" ");
if((i+1) % 10 ==0) {
System.out.println("...");
}
//System.out.print(" spot:"+i+" ");
//System.out.println("i:" +i +"count:"+count);
if(i>=count)
metCount = true;
}
}
}
}
...
我曾尝试在Eclipse中逐步执行,但仍然无法解决问题。它仅每隔一次发生一次。第一计数到4第二计数到10第三计数到4,依此类推。
After every new input line the value of
i
is reset to 0.Change your loop to, so previous value of
i
is retained