I wonder how to put a space between the output values in the Java coding output!

Asked 2 years ago, Updated 2 years ago, 17 views

We're coding the problem of finding prime factorization!

import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {

    int testcase = sc.nextInt();
    int n1;

    for(int i = 0; i < testcase; i ++) {
        n1 = sc.nextInt();

        while(n1 != 1){

            for(int j = 2; j <= n1; j ++){

                if(n1 % j == 0){
                    n1 /= j;

                    System.out.printf(j+" ");

                    break;
                    }
                }
            }
        }
    }
}

I don't think there's a problem with the coding itself, but I have a question about the value I print at the end.

If you output System.out.printf(j+"");

A number (blank) digit (blank) is output like (blank) and removes the last space.

I want to put a space between values only.

How can I search so many sites and use \t? I tried it, but I'm not sure ㅜ<

I'd appreciate your help!

java

2022-09-21 17:38

1 Answers

Java-like method: Create an array and String.join() Note

An Java way: This is how you fix the System.out.printf(j+" "); part from the source you uploaded.

if (i + 1 == testcase) { // only when the last i
  System.out.printf(j);
} } else {
  System.out.printf(j+" ");
}


2022-09-21 17:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.