繁体   English   中英

为什么我的代码不能第二次运行?

[英]Why won't my code run second time?

我正在做作业的某些代码有问题,当我第二次输入单词时,它不会重复。 我对Java还是很陌生,因此可以提供任何帮助。 谢谢

class Main
{
    public static void main( String args[] )
    {
        System.out.print( "#Please enter a word : " );
        String word = BIO.getString();

        int i, length, vowels = 0;
        String j;
        length = word.length();
        for (i = 0; i < length; i++)
        {

            j = word.substring(i, i + 1);

            if (j.equalsIgnoreCase("a") == true)
                vowels++;
            else if (j.equalsIgnoreCase("e") == true)
                vowels++;
            else if (j.equalsIgnoreCase("i") == true)
                vowels++;
            else if (j.equalsIgnoreCase("o") == true)
                vowels++;
            else if (j.equalsIgnoreCase("u") == true)
                vowels++;
        }
        System.out.print("[  " + vowels + "] vowels in " + "\""+word+"\"");

        System.out.print("\n");

        System.out.print("#Please enter a word : ");
        word = BIO.getString();

    }
}

为了获得期望的结果,您应该将代码嵌套在循环中。 像这样:

class Main
{
public static void main( String args[] )
{
    System.out.print( "#Please enter a word : " );
    String word = BIO.getString();

    while(!word.equals("QUIT")){

        int i, length, vowels = 0;
        String j;
        length = word.length();
        for (i = 0; i < length; i++)
        {

            j = word.substring(i, i + 1);

            if (j.equalsIgnoreCase("a") == true)
                vowels++;
            else if (j.equalsIgnoreCase("e") == true)
                vowels++;
            else if (j.equalsIgnoreCase("i") == true)
                vowels++;
            else if (j.equalsIgnoreCase("o") == true)
                vowels++;
            else if (j.equalsIgnoreCase("u") == true)
                vowels++;
        }
        System.out.print("[  " + vowels + "] vowels in " + "\""+word+"\"");

        System.out.print("\n");

        System.out.print("#Please enter a word : ");
        word = BIO.getString();
    }

}

这样,您的代码将循环播放,直到您输入单词QUIT。

在第二个输入执行之后,程序终止。 使用while(true)块和某种特殊输入(例如“ quit”或空字符串)来break循环。

做while循环是实现您想要的最佳方法! 如上所述,您尚未包括

System.out.print(“#请输入一个单词:”); 字= BIO.getString();

参与任何类型的循环。 因此,您不能期望代码会以其他方式运行。 包括它在一段时间内,你应该做得很好。 上面已经回答了一个经过很好修改的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM