我是Java的新手,并且遇到过一些问题,例如以下问题。我想从文本文档文件中读取几行,并在另一文本文档中从每一行中写入元音数。 “ vlez.txt”表示输入,而“ destinacija.txt”则输出。我感谢任何帮助我的人。 :) java code
编辑:如果我按此顺序输入字符串:
你好
世界
再见
在另一个文件中,我会得到这个:
2(来自Hello的2个元音)
3(来自世界+前一个元音)
7(您明白了。。]
package prvaZad;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class prvaZadaca {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("vlez.txt"));
PrintWriter out = new PrintWriter(new FileWriter("destinacija.txt"));
StringBuilder sb = new StringBuilder();
String line;
int number = 0;
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append('\n');
String lc = sb.toString().toLowerCase();
for (int i=0; i<lc.length(); i++) {
char ch = lc.charAt(i);
if ("aeiouy".indexOf(ch) > -1) {
number++;
}
}
out.print(number);
out.print('\n');
number = 0;
}
if (in != null)
in.close();
if (out != null)
out.close();
System.out.println(number);
}
}
问题是您不断在StringBuilder
上追加行,换句话说,它将从0开始重新计数。
您可以通过在下一次迭代之前“清除” StringBuilder
来解决此问题:
out.print(number);
out.print("\n")
number = 0;
sb = new StringBuilder(); // a new empty StringBuilder
此代码可以帮助您
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication11;
import java.util.Timer;
/**
*
* @author Sem-6-INGENIERIAINDU
*/
public class JavaApplication11 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String word = "Hello World Goodbye";
String[] container = word.split(" ");
for (String container1 : container) {
System.err.println("The word:" + container1 + " has " + (container1.replaceAll("[^aeiou]", "")).length());
}
}
}
运行:单词:Hello有2单词:World有1单词:再见有3建立成功(总时间:0秒)