2011-06-11 97 views
1

我试图用for循环来检查数组中的每个字符并打印字符,它在数组中的位置以及它是什么类型的字符(元音,辅音等)。我有这个至今:使用for循环检查数组

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."); 
      } 

如何打印的字符的位置

+0

有什么错,你有什么? – Adam 2011-06-11 03:20:54

+0

你正在寻找一种方法来确定当前正在检查的字母是元音还是辅音?看起来你在正确的轨道上,但你需要想出一个方法来确定那部分。 – 2011-06-11 03:22:36

+0

我不知道如何打印它是什么类型的字符。 – JDB 2011-06-11 03:23:03

回答

3

你在正确的轨道上(即“字符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); 
    } 
} 

你必须弄清楚什么你想在这里做。现在去做到这一点:)

编辑:要显示使用位置,这是一个有点笨拙,但还是更少的代码比标准的for循环

+0

只是一个小的补充,如果你真的在处理字符,更喜欢switch case然后如果。 – sangupta 2011-06-11 03:30:00

+0

谢谢。这真的很有帮助。还有一个问题......我将如何打印字符的位置(即“位于x处的字符x是元音”) – JDB 2011-06-11 03:35:17

+0

@JDB - 这就是为什么'for each'循环是**不合适的原因* *在这个特定的例子。 – 2011-06-11 03:52:36

0

提示:

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

  • Character类有许多用于分类字符和将大写字母转换为小写字母的方法&反之亦然。

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

  • 你也可以使用switch语句不同种类的信区分,并使用default分支的休息。

+0

我更新了代码。我在正确的轨道上吗? – JDB 2011-06-11 04:11:25

+0

种。你还没有处理大写字母,或者分类不是字母的字符,也不是空格。你需要走多远取决于问题是如何陈述的;即您可以对输入字符进行哪些假设。您现在也应该能够在输出中包含该位置。 – 2011-06-11 06:00:10

0
 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."); 
     } 
    ... }