[英]Scanning each character in Java from a file
I have a program which scans a text file and identifies whether or not each line starts with a vowel, however, I need to be able to scan each character to determine whether or not there are any vowels on the line and not just at the start. 我有一个程序可以扫描文本文件,并确定每行是否以元音开头,但是,我需要能够扫描每个字符以确定行上是否有元音,而不仅仅是在开始处。
String x = "";
Set<String> vowells = new HashSet<>();
vowells.add("a");
vowells.add("e");
vowells.add("i");
vowells.add("o");
vowells.add("u");
while (sc.hasNextLine()) {
readLine = new Scanner(sc.nextLine());
x = readLine.nextLine();
numberOfLines++;
if(vowells.contains(x.toLowerCase())) {
numberOfVowells++;
}
}
I have tried using while sc.hasNext
and tried using splitregex but I have had no luck so I thought maybe my error is something small and someone here could help me? 我曾经尝试使用
while sc.hasNext
并尝试使用splitregex,但是我没有运气,所以我认为我的错误可能很小,这里有人可以帮助我吗?
The question seems a little confusing, but if you are trying to just find vowels in the file, you can do it line by line. 这个问题似乎有些混乱,但是如果您试图在文件中查找元音,则可以逐行进行。 Here's some example code:
这是一些示例代码:
int numberOfVowells = 0;
String x = "";
String letter = "";
Set<String> vowells = new HashSet<>();
vowells.add("a");
vowells.add("e");
vowells.add("i");
vowells.add("o");
vowells.add("u");
File myFile = new File("Hello.txt");
Scanner sc = new Scanner(myFile);
while(sc.hasNextLine())
{
//take it in line by line
x = sc.nextLine();
//cycle through each character in the line
for(int i = 0; i < x.length(); i++)
{
letter = x.substring(i,i);
if(vowells.contains(letter.toLowerCase()))
{
numberOfVowells++;
}
}
}
I suppose if you wanted to count number of lines starting with vowels you could just add an if statement for when i is zero and it is a vowel. 我想,如果您想计算以元音开头的行数,则可以只添加一个if语句,用于当我为零且它是元音时。
You only have to use one Scanner
to read the file. 您只需使用一个
Scanner
即可读取文件。
File file = new File("the/path/to/your/file");
Scanner scanner = new Scanner(file);
Then you can use hasNextLine()
and nextLine()
to read the contents of your file line by line 然后,您可以使用
hasNextLine()
和nextLine()
读取文件的内容
String currLine;
while(scanner.hasNextLine()) {
currLine = scanner.nextLine();
//do something with currLine
}
In your case is seems you want to check if the current line starts with a vowel, so I would recommend first make the currLine
all lowercase and trimmed. 在您的情况下,您似乎想检查当前行是否以元音开头,因此我建议首先将
currLine
小写并修剪。
currLine = currLine.toLowerCase().trim();
Then you can use String functions like startsWith
and charAt
to do your checks. 然后,您可以使用
startsWith
和charAt
类的String函数进行检查。
Scanner filescan = new Scanner(new File("**your document/file**"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.