Home > Back-end >  Why is my for loop skipping the last iteration in java?
Why is my for loop skipping the last iteration in java?

Time:02-06

The third iteration of my for loop is only running once when it should be running twice.

First I have this array of words

String [] words = {"Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit.",,,,} 
spaceCount = 7;
wordCount = 4;
 while(wordCount>-1){
  output =words[start];
  System.out.println("output:" output);
  System.out.println("spaceCount:" spaceCount);
  System.out.println("wordCount:" wordCount);
  start  ;
  System.out.println("j<:" Math.ceil((double)spaceCount/(double)wordCount));
     for(j=0;j<Math.ceil((double)spaceCount/(double)wordCount);j  ){
       System.out.println("j:" j);
       output =" ";
       spaceCount--;
     }
  wordCount--;
 }

I tried to typecast the Math ceil from double to int but it still produce the same result.

The result that appear is:

output:Lorem
spaceCount:7
wordCount:4
j<:2.0
j:0
j:1
output:Lorem  ipsum
spaceCount:5
wordCount:3
j<:2.0
j:0
j:1
output:Lorem  ipsum  dolor
spaceCount:3
wordCount:2
**j<:2.0
j:0**
output:Lorem  ipsum  dolor sit
**spaceCount:2
wordCount:1**
j<:2.0
j:0
output:Lorem  ipsum  dolor sit amet,

but it should be:

output:Lorem  ipsum  dolor
spaceCount:3
wordCount:2
j<:2.0
j:0
j:1
output:Lorem  ipsum  dolor  sit
**spaceCount:1
wordCount:1
j<:1.0**
j:0
output:Lorem  ipsum  dolor  sit amet,

CodePudding user response:

The issue is with the calculation of the number of spaces that need to be added after each word. The calculation Math.ceil((double)spaceCount/(double)wordCount) always results in 2.0 when spaceCount is 7 and wordCount is 4. This causes the loop to run twice for the first three iterations, but only once for the last iteration.

To fix this issue, you can use a separate variable spacesPerWord to keep track of the number of spaces per word. Initialize spacesPerWord to Math.ceil((double)spaceCount/(double)wordCount) and decrement it after each iteration of the inner loop. Update the loop condition to be j < spacesPerWord. This will ensure that the correct number of spaces is added after each word.

Here's the updated code:

String [] words = {"Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit.",,,,}; 
int spaceCount = 7;
int wordCount = 4;
int spacesPerWord = (int)Math.ceil((double)spaceCount/(double)wordCount);
int start = 0;
String output = "";

while(wordCount > -1){
  output  = words[start];
  start  ;
  for(int j = 0; j < spacesPerWord; j  ){
    output  = " ";
    spaceCount--;
  }
  wordCount--;
  spacesPerWord = Math.max(1, spacesPerWord - 1);
}

System.out.println(output);
  • Related