for loop to while loop

2020-03-31 06:02发布

I am using a for loop to print the backwards alphabet in uppercase but I would like to know how to do the same thing with a while loop, which I am not very good with.

String alphabet = "abcdefghijklmnopqstuvwxyz";      
int x = 0;

for(x = alphabet.length() - 1; x > -1; x--) {
  System.out.print(alphabet.charAt(x));
  System.out.print(alphabet.toUpperCase());                 
}

I also need to terminate it when it reaches A. think it's something like this, but I don't know how to make it loop backwards. I'd really appreciate your help!

while(alphabet.length() < 26) {
  System.out.print(alphabet.charAt(x));  
  System.out.print(alphabet.toUpperCase());     
  if(x == A) {
    break;
  }     
}

标签: java loops
4条回答
太酷不给撩
2楼-- · 2020-03-31 06:44
for (initialization; condition; increment) {

}

is same as:

{
    initialization;
    while(condition) {
       // body
       increment;
    }
}

The outer block creates a block scope for the initialized parameter, that we get in a for loop also. But, if you are declaring your for-loop variable outside the loop, then you can omit that outer block.

Now you can map your for loop to the while loop.

查看更多
SAY GOODBYE
3楼-- · 2020-03-31 06:49
x = alphabet.length() - 1;
while( x > -1 )
    {
        System.out.print(  alphabet.charAt( x ));  
        System.out.print( alphabet.toUpperCase() );
        x--;
    }
查看更多
Rolldiameter
4楼-- · 2020-03-31 06:51

Try this:

public static void main(String[] args) {
  char[] alphabet =  "abcdefghijklmnopqstuvwxyz".toCharArray();
  int index = alphabet.length - 1;

  while (index >= 0) {
    System.out.println(alphabet[index--]);
  }
}

This is a most efficient solution with minimal memory overhead.

查看更多
时光不老,我们不散
5楼-- · 2020-03-31 06:53

There is a much simpler way to reverse a string in Java.

public class StringReversalExample {
    public static void main(String[] args) {
      String alphabet = "abcdefghijklmnopqstuvwxyz";
      String reversedString = new StringBuilder(alphabet).reverse().toString();
      System.out.println(reversedString);
    }
}
查看更多
登录 后发表回答