Home > Software design >  How do I store tokens into their own element in a given array?
How do I store tokens into their own element in a given array?

Time:10-22

I am trying to write a method that will use StringTokenizer to break up a user inputted String by a single space and store each word into their own array. The given code is as far I have gotten before getting stuck for 3 hours. I am trying to test out the code by having the for loop print out the elements of the array but all it does is return null for every element. What am I doing wrong? My best guess is that it is not assigning the array index to a token but I am not sure.. Any help would be amazing. Thank you!

Also, I know StringTokenizer is old legacy stuff but my professor strictly stated that he wants us to use it.

Thanks

private void receiveInput() {

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your command: ");
    String input = scanner.nextLine();
    StringTokenizer st = new StringTokenizer(input, " ");
    int number = st.countTokens();
    String tokenArray[] = new String[number];
    for (int i = 0; i < tokenArray.length; i  ) {
         System.out.println(tokenArray[i]);
    }
}

CodePudding user response:

String array tokenArray is initialized with size of tokens, but elements in the array are not assigned with values

require

tokenArray[i] = st.nextToken();

amended code

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your command: ");
String input = scanner.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
int number = st.countTokens();
String tokenArray[] = new String[number];
for (int i = 0; i < tokenArray.length; i  ) {
    tokenArray[i] = st.nextToken();
    System.out.println(tokenArray[i]);
}

CodePudding user response:

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your command: ");
    String input = scanner.nextLine();
    StringTokenizer st = new StringTokenizer(input, " ");
    while(st.hasMoreTokens()) {
        System.out.println(st.nextToken());
    }
  • Related