对于我的问题,我想起了很多人已经问过这个问题的提示,但我似乎找不到合适的答案。或答案是其他编程语言,对我没有帮助。所以我会再问一次:)
我必须从txt文件中读取内容,然后对数据进行一些数学运算。此数据为10000行,每行为20个数字,以分号分隔。为了从txt文件读取,我使用了BufferedReader,它给了我字符串。我可能必须将此字符串更改为int。到目前为止,一切都很好。然后我必须将其放入数组...怎么做?数组需要是二维的还是一维就足够了?
然后最后,我必须将结果写入不同的txt文件中。我必须写入可被3、11和5分开的不同文件编号,然后我必须对txt文件中的每一行求和并求出整个txt数字的总和。到目前为止我写的还好吗?我应该删除还是?
class Assignment {
public static void main (String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFile(nameFile);
List<Integer> divideNumber = stringToIntList(contentFile);
List<Integer> divisibleNo = processedData(divideNumber);
System.out.println(divideNumber);
}
private static String readFromFile(String nameFile) {
String content = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line = read.readLine();
while(line != null) {
System.out.println(line);
line = read.readLine();
content = line;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from the file");
}
return content;
}
private static List<Integer> stringToIntList(String contentFile) {
return Arrays
.stream(contentFile.split("; "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static int processedData(int divideNumber) {
try {
for(int i = 0; i < divideNumber; i++) {
if((divideNumber % 3 == 0) || (divideNumber % 5 == 0) || (divideNumber % 11 == 0)) {
System.out.println(divideNumber);
}
}
}
catch(NumberFormatException e){
System.out.println("It is not a number");
}
return divideNumber;
}
}
使用带有适当分隔符的扫描仪:
List<Integer> list = new ArrayList<>();
Scanner scanner = new Scanner(new FileInputStream(nameFile))
.useDelimiter("\\D+");
while (scanner.hasNext()) {
int i = scanner.nextInt();
list.add(i);
}