Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how do i split a string into characters using a scanner in java?

0 votes
asked Aug 6, 2021 by Ashwin (120 points)
My Code:

    Scanner kb = new Scanner (System.in);
    String ans;
      ans = kb.nextLine ();

    System.out.println(ans.split(" "));

1 Answer

0 votes
answered Sep 24, 2021 by Peter Minarik (55,660 points)

Please, read the documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

After this, it's easy to see why the following code works and why yours does not:

import java.util.Scanner;

public class Main
    public static void main(String[] args)
        String line = new Scanner(System.in).nextLine();
        String[] results = line.split(" ");
        for (String result : results)

If it's still not clear: String.split() returns an array of strings (the results of the split) and you have to iterate through them and print them one by one.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.