how do I eliminate the last character of an impression made by FOR in java?

2

I have:

for(i=0; i<vector.length; i++)
{
  System.out.print(Integer.toString(vector[i]) + " < ");
}

Example: The exit would be

  

1 < 2 < 3 < 4 <

This last sign I would like to eliminate from printing, try substring but being in a FOR , you can not. Can you help me?

    
asked by Whor 29.10.2017 в 06:07
source

2 answers

2

If what you want is to print something different in the last iteration of your loop, put a condition like this:

for(i=0; i<vector.length; i++)
{
  if(i==vector.length-1)
      System.out.print(Integer.toString(vector[i]));
  else
      System.out.print(Integer.toString(vector[i]) + " < ");
}

You also have the possibility to print all cases except the last one and then, once you have left the loop, print the last position.

for(i=0; i<vector.length-1; i++)
{
   System.out.print(Integer.toString(vector[i]) + " < ");
}

System.out.print(Integer.toString(vector[vector.length-1]));

I tried to touch the code as little as possible and make it understandable.

    
answered by 30.10.2017 / 08:20
source
3

A simple way to do the adjustment is to move the writing of the " < " in a separate statement, and adding a condition so that it is only written in all iterations except the first one:

for(i=0; i<vector.length; i++)
{
    if (i != 0) System.out.print(" < ");
    System.out.print(Integer.toString(vector[i]));
}

Another way is using String.join , available from Java 8. I assume that vector is an array of int . Sadly, in that case, the syntax is not as compact as one would like, but here it goes:

System.out.println(
    String.join(" < ", (Iterable<String>)Arrays.stream(vector)
                       .mapToObj(Integer::toString)::iterator));
    
answered by 29.10.2017 в 06:41