Search code examples
javaarraysspace

Removing space " " after last element


Extension to: Largest array / Comparing arrays (fresh view?)

Could someone give me a hint/solution how could I change code, so after the last output number it wouldn't add space after it?

import java.io.*;
import java.util.*;
public class Main {
  public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
 int[] productsAndCustomers = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
 int[] hind = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); 
 int[] raha = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();

    for (int m : raha) {
        int largest = Integer.MIN_VALUE;
        for (int p : hind) {
            if (p > largest && p <= m) {
                largest = p;
            }
        }
        System.out.print(largest + " ");
    }
  }
}

Although it shows the right answer, It has to be that it won't show that spacing after that last output number. What would be the best option?


Solution

  • You can create a variable space and initialize it with a space after the first iteration like this :

    String space = "";
    for (int m : raha) {
        //Your code...
        System.out.print(space + largest);
        space = " ";
    }