0

I've researched this subject thoroughly, including questions and answers on this website.... this is my basic code:

import java.util.Scanner;  
class StringSplit {  
public static void main(String[] args)   
{  
    System.out.println("Enter String");    
    Scanner io = new Scanner(System.in);  
    String input = io.next();  
    String[] keywords = input.split(" ");  
    System.out.println("keywords" + keywords);      
}   

and my objective is to be able to input a string like "hello, world, how, are, you, today," and have the program break up this single string into an array of strings like "[hello, world, how, are, you, today]... But whenever i compile this code, i get this output: "keywords = [Ljava.lang.String;@43ef9157" could anyone suggest a way for the array to be outputted in the way i require??

3 Answers 3

3

Sure:

System.out.println("keywords: " + Arrays.toString(keywords));

It's not the splitting that's causing you the problem (although it may not be doing what you want) - it's the fact that arrays don't override toString.

Sign up to request clarification or add additional context in comments.

2 Comments

Annoyingly don't override toString(). Can anyone explain why?
@DominicBou-Samra: Don't know, to be honest. By the time they found out it was annoying, it was probably too late...
0

You could try using Java's String.Split:

Just give it a regular expression that will match one (or more) of the delimeters you want, and put your output into an array.

As for output, use a for loop or foreach look to go over the elements of your array and print them.

The reason you're getting the output you're getting now is that the ToString() method of the array doesn't print the array contents (as it would in, say, Python) but prints the type of the object and its address.

2 Comments

The OP is using String.split().
Yeah, I saw that after I posted and was about to edit the reply. My bad.
0

This code should work:

String inputString = new String("hello, world, how, are, you, today");    
Scanner scn = new Scanner(inputString);
scn.useDelimiter(",");
ArrayList<String> words = new ArrayList<String>();
while (scn.hasNext()) {
   words.add(scn.next());
}

//To convert ArrayList to array
String[] keywords = new String[words.size()];
for (int i=0; i<words.size(); ++i) {
   keywords[i] = words.get(i);
}

The useDelimiter function uses the comma to separate the words. Hope this helps!

1 Comment

This is just a different way to split the String up into a String Array. The OP's problem is printing the resulting array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.