-2

I am trying to find a way where i can get the user to enter a string e.g. "Hello my name is mr. blobby" then break this down into individual chars and print them out so it prints them out like so:
{'H', 'e', 'l', 'l', 'o', 'm', 'y'}

so far i have this:

String userInputString;

        HashMap hm = new HashMap();
        Scanner userInput = new Scanner( System.in );
        System.out.println("Type a string: ");
        userInputString = userInput.next();

        char ui = userInputString.charAt(0);
        char[] ui_arr = userInputString.toCharArray();

        for(int i=0;i<ui_arr.length;i++){
            System.out.print(String.valueOf(ui_arr[i]));

this takes the input from the user and prints them out. however, i want them to be printed comma seperated rather than they are typed in. thanks

Obese Octopus
  • 101
  • 1
  • 2
  • 11
  • 1
    One thing you should start to learn is to read JavaDoc if you don't know how a certain API/method works. So I suggest you to read these two docs: [PrintStream#println](http://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#println-java.lang.String-) and [Scanner#next](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--) (bonus: [Scanner#nextLine](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--)). – Tom Oct 05 '15 at 10:26
  • Use System.out.print rather than println. "ln" means "new Line". Because when you use scanner you should tell userInput variable to read nextLine() not next() parameter. By default as an argument when you call next() it splits your input via "space" character. – Afsin Buyuksarac Oct 05 '15 at 10:27

5 Answers5

2

You can use the Streams API to join the characters in the String with a , between them.

Scanner userInput = new Scanner( System.in );
// read a whole line instead of a word.
// split into all characters and turn into a Stream
// join all the chaarcters with a `,` between them.
System.out.println(Stream.of(userInput.nextLine().split("", -1))
                         .collect(Collectors.joining(",")));
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

So there are a couple of mistakes I see in your code.

HashMap hm = new HashMap(); 

This line is useless. You don't use hm anywhere.

Scanner userInput = new Scanner( System.in ); 
System.out.println("Type a string: "); 

Okay

userInputString = userInput.next(); 

the next() method only reads up to the next space. You want to be using nextLine(), which reads the entire line.

char ui = userInputString.charAt(0); 

I don't see where you use this either...?

char[] ui_arr = userInputString.toCharArray(); 

Okay

for(int i=0;i<ui_arr.length;i++){
    System.out.println(String.valueOf(ui_arr[i]));
}

Wrong method again, println() prints the character and then a newline, i.e. it presses Enter afterwards. You want to be using print(). In addition to this, you don't need to convert a char to a String, you can immediately print a char (i.e. System.out.print(ui_arr[i]);).

If you want to separate the chars by comma, you will need to use print(ui_arr[i] + ", "). This will print the character, and then ,. To make it even better you need to check in your code if it is the last character and then omit printing ,.

So in general I'd suggest this:

Scanner userInput = new Scanner(System.in);
System.out.println("Type a string: ");
String userInputString = userInput.nextLine();

char[] ui_arr = userInputString.toCharArray();

for(int i=0; i<ui_arr.length; i++){
    System.out.print(ui_arr[i]);
    if(i < ui_arr.length - 1){
        System.out.print(", ");
    }
}
Jari
  • 39
  • 1
  • 6
  • 1
    Options are : `Arrays.deepToString(ui_arr.toArray())` then removing the `[` and `]` . – Marcel Oct 05 '15 at 10:43
  • 1
    I agree, but judging from his post we should keep this as simple as possible, using methods known to beginners. – Jari Oct 05 '15 at 10:44
  • @Marcel *"Options are : `Arrays.deepToString(ui_arr.toArray())` then removing the `[` and `]`"* ... you should rethink that comment. First where does the method `toArray()` come from? And why do you want to use `deepToString`? Where do you see the 2d array? – Tom Oct 05 '15 at 10:48
  • You are right, i am used to working with lists and maps, not arrays. the `toArray()` is unnecessary, and `toString()` would fit your needs as well, however i'd preffer the `deepToString()` cause you can always use that one. – Marcel Oct 05 '15 at 12:54
  • But that implies something about the passed argument, that it can't fulfill. But yes, it would work. – Tom Oct 05 '15 at 13:04
1

Ty this:

Scanner userInput = new Scanner( System.in );
        System.out.println("Type a string: ");
        char[] userInputString = userInput.nextLine().toCharArray();

       for(int i = 0; i < userInputString.length; i++){
           if(!String.valueOf(userInputString[i]).equals(" "))
               System.out.print(userInputString[i]+",");
       }

You can also add the condition where you dont want to print space using if condition.

Ankush soni
  • 1,439
  • 1
  • 15
  • 30
0

Use userInput.nextLine() instead of userInput.next() then you can format your string as you want and then print it. Just pay attention to javadoc to know how exactly the functions act.

here is an example:

    Scanner userInput = new Scanner(System.in);
    System.out.println("Type a string: ");
    String userInputString = userInput.nextLine();

    char[] ui_arr = userInputString.toCharArray();

    StringBuffer sb = new StringBuffer("{");
    for (char c: ui_arr) {
        sb.append(c);
        sb.append(",");
    }
    // delete the last comma
    sb.deleteCharAt(sb.length() -1);
    sb.append("}");
    System.out.println(sb.toString());

You can do whatever you want inside the for loop for example ignoring space char or other thing

Hope that helps

jMounir
  • 495
  • 2
  • 11
0

The given task can be easily done by just having the string, there is no need to convert it into a char array and then print them individually.

just iterate the string from beginning to end(its length), if the character is a space, just ignore, else print it. System.out.println() prints the content followed by a newline, System.out.print() prints the content only. Modified code:

Scanner userInput = new Scanner( System.in );
    System.out.println("Type a string: ");
    String userInputString = userInput.nextLine();

    for(int i=0;i<userInputString.length();i++){
        if(userInputString.charAt(i)!=' ')
        System.out.print(userInputString.charAt(i)+" ");
    }

enter code here

If you really want to convert the string into a char array and the output should exactly match like {'H', 'e', 'l', 'l', 'o', 'm', 'y'}. 1. Remove all the spaces in the string. 2. Convert it into an array. 3. print the array.

jeffry copps
  • 305
  • 5
  • 22