Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有人能帮我弄清楚为什么我陷入了困境吗?我能写得更简单些吗?_Java - Fatal编程技术网

Java 有人能帮我弄清楚为什么我陷入了困境吗?我能写得更简单些吗?

Java 有人能帮我弄清楚为什么我陷入了困境吗?我能写得更简单些吗?,java,Java,我的目标是把一个单词的第一个字母移到最后,直到第一个字母是元音。这是猪拉丁语 System.out.println("Enter a word: "); String word = keyboard.nextLine(); String y = word.substring(0,1); String z = word.substring(1); char x = Character.toLowerCase(word.charAt(0)); if

我的目标是把一个单词的第一个字母移到最后,直到第一个字母是元音。这是猪拉丁语

    System.out.println("Enter a word: ");
    String word = keyboard.nextLine();
    String y = word.substring(0,1);
    String z = word.substring(1);

    char x = Character.toLowerCase(word.charAt(0));

    if ((x=='a') || (x=='e') || (x=='i') || (x=='o') || (x=='u')) {
        System.out.println(word + "ay ");
    } 

    while ((x!='a') || (x!='e') || (x!='i') || (x!='o') || (x!='u')) {
        String s = z+y;
        System.out.println(s);
    }

您一直在对变量x进行检查,但没有在循环体中更新其值。因此,这种情况不断得到验证。 换句话说

第一次迭代:x和元音不同吗? 如果是,则构建s字符串并打印它 第二次迭代:x和元音不同吗? 和2一样。。。等等
您的错误是,在while循环中,您从未更新x的值。因此,程序永远不会终止。为了使你的猪拉丁文更易于阅读和调试,你应该考虑将程序分解成方法。

例如:

public static boolean isVowel(char input){
    input = Character.toLowerCase(input);
    return ((input=='a') || (input=='e') || (input=='i') || (input=='o') || (input=='u'));
}
这样你就能做到:

System.out.println("Enter a word: ");
String word = keyboard.nextLine();

while (!isVowel(word.charAt(0))){ //while the first character isn't a vowel do this:
    word = word.substring(1) + word.charAt(0);
}

System.out.println(word);
但是要注意,如果没有元音,这个程序仍然会运行在一个无限循环中

如果没有方法,代码将如下所示:

System.out.println("Enter a word: ");
String word = keyboard.nextLine();

char currentChar = Character.toLowerCase(word.charAt(0));
while (!((currentChar=='a') || (currentChar=='e') || (currentChar=='i') || (currentChar=='o') || (currentChar=='u'))){ //while the first character isn't a vowel do this:
    word = word.substring(1) + word.charAt(0);
    currentChar = Character.toLowerCase(word.charAt(0));
}

System.out.println(word);

希望这有帮助:

是的,它有一点帮助。但目前我对使用这些方法还是不太自信。整个代码看起来怎么样?@duBz180我添加了一段代码,不需要使用方法就可以工作。