我必须做一个 java 实验室,它将输入一个句子并创建一个新字符串,其中只有以元音开头的单词。
例子:
输入:这是一个炎热潮湿的夏日。
输出:Itisaand。
编辑:我得到的输出是anananananan。
这是我的代码(带注释)。方法很简单。我只是不确定为什么这不起作用。
import java.util.*;
public class Driver {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Input: ");
String input = console.nextLine();
Class strings = new Class(input);
// class has constructor for input
int beg = 0, end = 0;
for (int j = 0; j < input.length(); j++) {
if (strings.isVowel(j) && (input.charAt(j - 1) == ' ' || j == 0))
beg = j;
// isVowel finds if there is a vowel at the location
else if (strings.endWord(j))
end = j - 1;
// endWord finds if there is a space or punctuation at the location
if (beg == end - 2)
strings.findWord(beg, end);
// findWord adds a substring of input from beg to end to the answer
}
System.out.print("\nOutput: ");
strings.printAnswer();
// printAnswer prints the answer
}
}
编辑:这是我班级的代码。
public class Class {
String input = "", answer = "";
public Class(String input1) {
input = input1;
}
public boolean isVowel(int loc) {
return (input.charAt(loc) == 'a' || input.charAt(loc) == 'e' || input.charAt(loc) == 'i'
|| input.charAt(loc) == 'o' || input.charAt(loc) == 'u');
}
public boolean endWord(int loc) {
return (input.charAt(loc) == ' ' || input.charAt(loc) == '.' || input.charAt(loc) == '?'
|| input.charAt(loc) == '!');
}
public void findWord(int beg, int end) {
answer = answer + (input.substring(beg, end));
}
public void printAnswer() {
System.out.println(answer + ".");
}
}