user4309460
user4309460

Reputation:

Create a string array with length determined by user input

I am trying to create an array that reads string tokens from standard input, and places them in an array, and then prints the words out, until it reaches a specific word. For example, let's say I wanted my array to read a series of words until it reached the word "okay" from std in, print out each word, and then terminate before printing out "okay". The length of this array will be unknown, so I am confused on how to do this.

     String s  = sc.next();
     String[] copy = new String[???];

     for( int i = 0; i < copy.length; i++ ){
           copy[i] = sc.next();     
     }

Upvotes: 1

Views: 1419

Answers (3)

Peter Pan
Peter Pan

Reputation: 24148

It's my code Without using ArrayList.

import java.util.Scanner;
import java.util.StringTokenizer;
public class Sample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System. in );
        String line = sc.nextLine();
        StringTokenizer st = new StringTokenizer(line);
        int len = st.countTokens();
        String[] array = new String[len];
        for (int idx = 0; idx < len; idx++) {
            array[idx] = st.nextToken();
        }
        for (String str: array) {
            System.out.println(str);
        }
    }
}

Upvotes: 0

anindyaju99
anindyaju99

Reputation: 475

If you don't want to use any list at all, then this becomes impossible. This is simply because array size needs to be defined at the time the array object is created.

So with this constraint you can have a large integer and declare an array of that size.

Final int MY_LARGE_CONST = 3000; ... String[] tokens = new String[MY_LARGE_CONST]...

This is wasteful since it takes more memory and will fail if you have more tokens than the constant.

Alternaely if you are ok with lists and not ok with iterating over that for actual processing, then u can put the tokens in an ArrayList and once they are all collected, call the toArray method on the ArrayList object.

Upvotes: 0

Michael
Michael

Reputation: 2773

Something like:

 String s  = sc.next();
 ArrayList<String> copy = new ArrayList<String>();
 while(!s.equals("okay")){
      copy.add(s);
      s = sc.next();
 }

 for (String n : copy){
      System.out.println(n);
 }

Upvotes: 2

Related Questions