简体   繁体   中英

Adding two or more nested for loops in a JAVA programme

I am just a beginner in JAVA and while doing a class tutorial I got this problem. This is the output I should get:

  1    
 123
12345
 123
  1

I wrote this code and it gives a compilation error at line 16 saying that "for(int k=1; k<=5-i; k++)" is an unreachable statement.

 public class CaseThree{ public static void main (String[] args){ for(int a=1; a<=3; a++){ for(int b=1; b<=3-a; b++){ System.out.print(" "); } for(int c=1; c<=2*a-1; c++){ System.out.print(c); } System.out.println(); } for(int i=1; i<=2; i++){ for(int j=1;; j++){ System.out.print(" "); } for(int k=1; k<=5-2*i; k++){ System.out.print(k); } System.out.println(); } } } 

What is wrong with this code? (Our lecturer told us to use two separate nested for loops.)

Look at the code right before the statement that the compiler says that is impossible to reach

for(int j=1;; j++){
    System.out.print(" ");
}

the validation expression is empty, hence this is an infinite loop which explain the compilation error.

for(int j = 1; \\这是什么?\\; j ++)

第13行的无限循环。无需条件检查即可结束循环。而且,对于此类输出,您不需要那么多的for循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM