for循环到while循环 [英] for loop to while loop

查看:104
本文介绍了for循环到while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用for循环将大写的向后字母打印出来,但是我想知道如何对while循环执行相同的操作,但我不太擅长.

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());                 
}

我还需要在到达A时终止它.以为是这样,但是我不知道如何使它向后循环.非常感谢您的帮助!

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;
  }     
}

推荐答案

for (initialization; condition; increment) {

}

与:

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

外部块为初始化的参数创建一个block范围,我们也进入了for循环.但是,如果在循环之外声明for-loop变量,则可以省略该外部块.

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.

现在,您可以将for循环映射到while循环.

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

这篇关于for循环到while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆