-8

I wan't to use the scanner to ask for input a few words and am expecting a delimiter ", " to separate each word. I then want to split each word and store it in an array so I could use it for other purposes i.e, instantiate an object with an array argument for my constructor. Could someone help me please

Update: I have resolved the problem! Thanks everyone for the suggestions.

ferics
  • 77
  • 7
  • You can post your code in question @ChanbothSom – Adya May 18 '18 at 15:20
  • 1
    What do you mean by nasty? – Thiyagu May 18 '18 at 15:20
  • http://prntscr.com/jjl1kw When I tried inputting " a, b " after the split I got [Ljava.lang.String;@27abe2cd – ferics May 18 '18 at 15:23
  • -1 for this vague update _I have resolved the problem! Thanks everyone for the suggestions_. You should tell us what solved your problem or accept one of the answer, generally questions in SO should be able to help future visitors. – Pradeep Simha May 18 '18 at 15:38
  • Can you edit the code into your question please? –  May 19 '18 at 07:44

3 Answers3

1

If I understand your question correctly, this is that I would do

Scanner keyb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String input = keyb.nextLine();
String[] stringArray = input.split(",");

To see the results:

for(int i=0; i < stringArray.length; i++){
    System.out.println(i + ": "  + stringArray[i]);
}

This will work for any size sentence as long as each word is separated by a ,.

GreenSaber
  • 1,118
  • 2
  • 26
  • 53
0

You can do this using a loop and checking with Scanner.hasNext(). Like so:

Scanner k = new Scanner(new File("input.txt"));
k.useDelimiter(",");
LinkedList<String> words = new LinkedList<String>();
while(k.hasNext()){
    words.add(k.next());
}
System.out.println(words);

Notice how I set the delimiter to be a comma, so that each next read word is distinguished as being separated by commas.

dsillman2000
  • 976
  • 1
  • 8
  • 20
0
import java.util.*;

public class testing {

    public static void main (String[] args) {
        String splitter = ",";
        Scanner scanner = new Scanner(System.in);
        System.out.println("user input:");
        String[] fewwords = scanner.nextLine().split(splitter);
        System.out.println(fewwords[0] + fewwords[1] + fewwords[2]);
    }
}
wutBruh
  • 67
  • 10
  • btw, the system.out.println onlu works if u have 3 words now obviously (so if u want to see all of them no matter what the length is, use a for loop like @GreenSaber answered. We basically wrote the same thing. – wutBruh May 18 '18 at 15:33