Java如何不使用数组循环输出2、5、7、10、12?
不使用数组循环输出指定数字的几种方法
你要输出的数字是2、5、7、10、12,不用数组的话,有几个简单的思路:
方法一:for循环+switch控制数值变化
这种方法适合新手理解,先定义初始数字,循环对应次数,每次输出后根据当前数字调整下一个值:
public class Main { public static void main(String[] args) { int num = 2; // 循环5次,正好输出5个数字 for (int i = 0; i < 5; i++) { System.out.println(num); // 根据当前数字确定下一个数 switch(num) { case 2: num += 3; break; case 5: num += 2; break; case 7: num += 3; break; case 10: num += 2; break; } } } }
方法二:while循环+条件判断
和上面思路类似,用while循环计数,通过if-else判断数值的增量:
public class Main { public static void main(String[] args) { int current = 2; int outputCount = 0; // 输出够5个就停止循环 while (outputCount < 5) { System.out.println(current); // 2和7之后要加3,其他加2 if (current == 2 || current == 7) { current += 3; } else { current += 2; } outputCount++; } } }
方法三:循环中直接枚举数值(最直观)
如果不想处理数值变化,也可以把要输出的数字直接写到循环里,对新手来说更容易理解:
public class Main { public static void main(String[] args) { // 循环5次,每次对应一个数字 for (int i = 0; i < 5; i++) { switch(i) { case 0: System.out.println(2); break; case 1: System.out.println(5); break; case 2: System.out.println(7); break; case 3: System.out.println(10); break; case 4: System.out.println(12); break; } } } }
这些方法都不需要用到数组,都是用基础的循环和分支语句实现的,你可以根据自己的理解选择其中一种。
内容的提问来源于stack exchange,提问作者arownz
相关产品推荐
相关产品推荐

