简体   繁体   中英

Program into infinite loop -Java

I am trying to solve a problem using java where I have to print the number the same number of time as the number itself. For example 1 will be printed once 2 twice 3 thrice and so on. I tried to attempt the question using nested loop but it is going into infinite loop. Please pinpoint the mistake in the code. Thanks!

 {                                         
    for (int i=1;i<=10;i=i+1) {
        for (int j=1;j<=i; j=i) {
            jTextArea1.append(""+j);
        }
    }
 }          

PS I attempted this question using netbeans.

The problem is in the second loop.

Making progress as j=i and checking for j<=i will always give the true result. So there is the infinite loop.

You may want to change the progress to something like j= j+1

Edit: You need to do this

for (int i=1;i<=10;i=i+1) {
    for (int j=1;j<=i; j++) {
         jTextArea1.append(""+i);
    }
}

The problem caused in second loop during initialize j = i . This interrupt the var j to be increment. It should be j++ or j += 1 or j = j + 1 . Example here...

for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= i ; j++) {
       jTextArea1.append(" "+i);
    }
}

Use this see what is happening. I've simplified your code a bit:

for (int i=1; i<=10; i++){
   for (int j=1; j<i; j=i){
      System.out.println("j=" + j + ", i=" + i);
   }
}

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