繁体   English   中英

使用 for 循环检查数组

[英]Using a for-loop to examine an array

我正在尝试使用 for 循环检查数组中的每个字符并打印字符,它是数组中的 position,以及它是什么类型的字符(元音、辅音等)。 到目前为止我有这个:

char[] myName = new char[] {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e'};

         System.out.print("\nMy name is: ");

            for(int index=0; index < myName.length ; index++)
            System.out.print(myName[index]);

            for(char c : myName) {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            {
                System.out.println("The character located at position is a vowel.");
            }
            else if (c == 'j' || c == 'h' || c == 'n' || c == 'd')
            {
                System.out.println("The character located at position is a consonant.");
            }
            else if (c == ' ')
            {
                System.out.println("The character located at position is a space.");
            }

如何打印字符的位置(即“位于 position x 的字符 x 是元音。”)

你在正确的轨道上。 您的循环没问题,但如果您实际上不需要索引,请尝试使用foreach语法,如下所示:

 char[] myName = new char[] {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e'};

 System.out.print("\nMy name is: ");

 for(char c : myName) {
     System.out.print(c); 
 }

现在添加一些逻辑:

 int i = 0;
 for(char c : myName) {
     i++;
     // Is the char a vowel?
     if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
         // do something - eg print in uppercase
         System.out.print(Character.toUpperCase(c) + " at position " + i);
     } else {
         // do something else - eg print in lowercase
         System.out.print(Character.toLowerCase(c) + " at position " + i);
     }
 }

你必须弄清楚你想在这里做什么。 现在 go 这样做:)

编辑:展示 position 的使用,这有点笨拙,但代码仍比标准 for 循环少

提示:

  • 您应该使用当前使用的那种for循环。 值索引变量将在您的 output 中有用。

  • 字符 class 有多种分类字符的方法,以及从大写到小写的转换,反之亦然。

  • 您还可以使用==来测试字符...

  • 您还可以使用 switch 语句来区分不同类型的字母,并使用 rest 的default分支。

     char[] myName = new char[] {'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e'};

     System.out.print("\nMy name is: ");

        for(int index=0; index < myName.length ; index++)
        char c = myname[index];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        {
            System.out.println("The character " + c + "located at position " + index + " is a vowel.");
        }
    ... }

暂无
暂无

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

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