这是为了回答我关于解决我的一个程序的许多问题。所以现在,我正在尝试计算输入的文本文件中元音的数量,然后将其输出回文本文件。但是,在这种情况下,我还需要将文本文件中的任何空格更改为波浪号/波浪号(~)。如果你看一下大量 if 语句块之后的行,有一个 if 语句说明字符是否为空格,然后将其更改为波浪号。
我知道字符串是不可变的,所以这就是为什么我不确定如何更改它。我真的不想要一个新字符串……但这可能是我唯一的选择。
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next();
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
if (sentence.toLowerCase().charAt(i) == ' '){
}
}
System.out.println("The number of A vowels is: " + numOfVowelsA);
System.out.println("The number of E vowels is: " + numOfVowelsE);
System.out.println("The number of I vowels is: " + numOfVowelsI);
System.out.println("The number of O vowels is: " + numOfVowelsO);
System.out.println("The number of U vowels is: " + numOfVowelsU);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}