0
for (int page = 0; page < pageNum;) {
    copy.addPage(copy.getImportedPage(reader, ++page));
}

here ++page is control variable getting modified , how to achieve in better way ?

2
  • 1
    Do you really want the preincrement (++page)? Commented Aug 10, 2015 at 10:07
  • 1
    better, in what sense? Do you just want to improve readability, or also functionality? Commented Aug 10, 2015 at 10:09

4 Answers 4

4

Try using the while when you do not have the control over increment operation

int page=0;
while(page<pageNum){
    copy.addPage(copy.getImportedPage(reader, ++page));
}
Sign up to request clarification or add additional context in comments.

Comments

3

Do you mean this?

for (int page = 0; page < pageNum; page++) {
    copy.addPage(copy.getImportedPage(reader, page+1));
}

6 Comments

To have exactly the same behavior, I think it must start at page = 1. OP is using preincrement operator. I wonder if that's actually what he wants to do, though.
no , actually inside addPage method page variable need to be first incremented and passed and then loop with incremented value
@user1659644 your question is unclear then. State what you want to achieve, what you are getting instead, and why this is wrong
@Fildor nah, to have exactly the same behavior, simply change this: copy.getImportedPage(reader, page + 1)
This can be achieved using a while instead of for
|
1
copy.addPage(copy.getImportedPage(reader, ++page));

using pre-increment operator the value will be updated first

i.e it will be called with the incremented value of page which is 1

copy.addPage(copy.getImportedPage(reader, page++));

using post-increment operator the value will be updated after

i.e it will be called with the non incremented value of page which is 0

use the pre or post increment operator according to your requirement.

Comments

0

You can do it in different ways

1

        for (int page = 1; page <= pageNum; ++page) {
            copy.addPage(copy.getImportedPage(reader, page));
        }

2

        for (int page = 1; page <= pageNum; page++) {
            copy.addPage(copy.getImportedPage(reader, page));
        }

3

        int page = 1;
        while (page <= pageNum) {
            copy.addPage(copy.getImportedPage(reader, page));
            page++;
        }

4

        int page = 0;
        while (page < pageNum) {
            page++;
            copy.addPage(copy.getImportedPage(reader, page));
        }

5

        int page = 0;
        while (page < pageNum) {
            copy.addPage(copy.getImportedPage(reader, ++page));
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.