我有一项作业,必须获取用户输入的名称并将元音转换为星号。我有分配协议(protocol)的这一部分(正如您将在下面的代码中看到的那样),但还有另一部分:如果输入的字符串具有偶数个字符,则第一个字符之间应该有两个而不是一个空格和姓氏。如果是奇数,应该只有一个。我尝试使用 if-else 语句来实现这一点,但它无法正常工作。
如果有帮助,我们将不胜感激。谢谢。
import java.util.*;
import java.io.*; // necessary for user input
public class Prog510a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String word = input.nextLine();
int length = word.length();
String space = "";
for(int count = 0; count < word.length(); count ++)
{
char c = word.charAt(count);
if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O'
|| c == 'u' || c == 'U')
{
String front = word.substring(0, count);
String back = word.substring(count + 1);
word = front + "*" + back;
}
}
if (length % 2 == 0)
{
space = " ";
}
else
{
space = " ";
}
System.out.println(word);
}
}
最佳答案
嗯,您可能想首先将全名拆分为名字和姓氏。这可以使用 split 函数来完成,该函数返回一个字符串数组:
string[] firstAndLastNames = word.split(" ");
这当然是在替换元音之后完成的,但并非必须如此。
然后您只需获取全名的长度,并适本地分配给 space
变量即可:
if ((firstAndLastNames[0].length() + firstAndLastNames[1].length()) % 2 == 0)
space = " ";
else
space = " ";
然后当你输出它时,执行如下操作:
System.out.println(firstAndLastNames[0] + space + firstAndLastNames[1]);
我还推荐一种用星号替换元音的更好方法,因为它非常困惑。最好创建一个元音数组,并使用 equalsIgnoreCase 函数来替换:
string[] vowels = {"a","e","i","o","u"};
for (int i = 0; i < vowels.length; i++}
for (int j = 0; j < word.length; j++)
if (word[j].equalsIgnoreCase(vowel[i]))
word[j] = "*";
由于您还没有学习数组,您可以使用字符串 replace
函数根据长度将空格替换为一个或两个空格,例如:
if (word.length() % 2 == 0)
word = word.replace(" "," ");
你不需要检查它是否奇数,因为它已经有 1 个空格,这就是你想要的。
关于java - 用星号替换元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27209240/