nested for loop for alphabet increment

倖福魔咒の 提交于 2019-12-12 06:57:01

问题


I have searched everywhere and I cannot figure out how to create this output using a nested for loop in java:

"a

ab

abc

abcd"

continued until z

this is what I have tried

String alphabet = "abcdefghijklmnopqrstuvwxyz";

    for(int i = 0; i <= 25; i++)
    {
        for(char j = (char)(alphabet.charAt(i)); j<=i; j++)
        {

        System.out.print(j);
        }
        System.out.println();
    }

Please help me!


回答1:


Here is the answer:

    for (int x = 'a'; x<='z'; x++)
   {
        for (int i = 'a'; i<=x; i++)
        {
          System.out.print((char)i);
        }
        System.out.println();

    }

The outer loop switches from one row to another whilst the inner loop prints the characters for that particular row.




回答2:


Here you go !

print capital Alphabet

  public class Main
    {
  public static void main(String[] args)
    {
        int i, j;
        for(i = 1; i<=26; i++)  {
        for(j = 1; j <= 1-i; j++) {
        System.out.print(" ");
        for(j = 1; j <= i; j++) 
        System.out.print((char)(char)(i+64)+" ");
        System.out.println(); //for line break
          }
      }
  }


来源:https://stackoverflow.com/questions/23206148/nested-for-loop-for-alphabet-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!