Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

increment operator in while loop

 
uzma Akbar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class JMM124 {
public static void main(String args[]) {
int a = 0;
while (a++ < (args.length-1) ) {
System.out.print(args[a]);
}

}}

Please explain when we run the program why nothing is printed?
Any help is appreciated.

Uzma
 
Gyanesh Sharma
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java JMM124 "1" "2"
prints
2
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using args.length - 1?
 
uzma Akbar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using args.length-1 because without -1 it throws run time exception. I was trying JMM124 abcde...so nothing was printed as I was not using spaces in between. Thanks for your help

uzma
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by uzma Akbar:
I am using args.length-1 because without -1 it throws run time exception...

This is a little odd, so I just want to be sure you understand what's happening here.

When incrementing through an array, it's common to start the index at zero and use a test like "< args.length."

But in this case, the index is being incremented after the test: "a++ < args.length."

Using "args.length - 1" is one way to avoid a NullPointerException, but if you initialize your counter to zero, then you're also going to miss the first array element (at index 0).
 
Gyanesh Sharma
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could write the program as follows to avoid the runtime exception:

class JMM124 {
public static void main(String args[]) {
int a = 0;
do {
System.out.print(args[a]);
}
while (++a < (args.length));

}}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or simply use args[a-1] (along with the original while loop and the postfix increment).
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or write it conventionally thus:




In that case you can easily use the for loop to write it a more understandable way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic