Java Noob
Java Noob

Reputation: 371

How do i declare custom generated strings inside a while loop?

What I'm trying to do is to declare a certain amount of strings according to the amount of tokens a scanner scans in a single input, then have these strings equal the next input. This is what I'm trying:

int numberOfTokens = 0;

boolean mainLoop = true;

Scanner input = new Scanner(System.in);

while(mainLoop == true)
{
   while(input.hasNext())
   {
      String int(+ numberOfTokens) = input.next(); (this doesn't work)
      numberOfTokens += 1;
   }
}

I hope I made it clear of what I am trying to do. I tried using String arrays, but they won't work for what i'm trying to do. Thanks.

Upvotes: 0

Views: 52

Answers (3)

John Bollinger
John Bollinger

Reputation: 180968

If you don't know in advance how many strings you will need to store then an array is a poor choice of data structure, at least during the input phase. Use a List instead -- these keep the elements in order, yet expand as needed to accommodate new elements. They are convenient to work with overall, but if you ultimately must get the strings in array form (e.g. because some external API requires that form) then it is easy to obtain the corresponding array.

For example:

List<String> tokens = new ArrayList<>();

while (input.hasNext()) {
    tokens.add(input.next());
    // a List keeps track of its own length
}

If you later wanted the array then you could do

String[] tokenArray = tokens.toArray(new String[0]);

The number of tokens recorded in the List is available at any time as tokens.size(), or after you convert to an array, as tokenArray.length.

In any event, you cannot create new variables at runtime in Java.

Upvotes: 0

Roland Illig
Roland Illig

Reputation: 41676

Instead of string variables, you should declare one variable like this before the while loop.

List<String> tokens = new ArrayList<>();
while (input.hasNext()) {
  tokens.add(input.next());
}

You can then operate on the tokens, like this:

int n = tokens.size();

for (String token : tokens) {
  System.out.println(token);
}

Upvotes: 0

You can do:

String[] myStringArray = new String[abc];

where abc is an integer you get from user

and then

myStringArray[index]  = input.next();

and index must be a valid number between 0 and abc

Upvotes: 1

Related Questions