0

I want the folowing program to take user input, store it in the array then repeat it back when the user types stop.

However it prints out the rest of the values upto 100 as null, this is what I need to remove. I've tried a few different methods but it's just not working for me.

This is basically what I've got so far (with help from other questions on Stack):

public static void main(String[] args) {

    String[] teams = new String[100];
    String str = null;
    Scanner sc = new Scanner(System.in);
    int count = -1;
    String[] refinedArray = new String[teams.length];

    for (int i = 0; i < 100; i++) {       
       str= sc.nextLine();


       for(String s : teams) {
           if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
               refinedArray[++count] = s; // Increments count and sets a value in the refined array
           }
       }

       if(str.equals("stop")) {
          Arrays.stream(teams).forEach(System.out::println);
       }

       teams[i] = str;
    }
}
2
  • Maybe you can convert teams to a List and then truncate it like it says at stackoverflow.com/questions/1279476/… Commented Jun 21, 2017 at 14:24
  • @ZeldaZach there is no need to truncate a List in this case. It will contain only the elements that were added. Commented Jun 21, 2017 at 14:30

2 Answers 2

1

An array as has a fixed size and if you use an array of an any class, you will have null value for indexes of the values not valued.

If you want to have a array with only used values, you could define a variable to store the size really used by array.
And use it to create a new array with the actual size.

Otherwise you could use the original array but iterating only until the actual size of the array when you loop on String[] teams.

String[] teams = new String[100];
int actualSize = 0;
...
for (int i = 0; i < 100; i++) {       
   ...

   teams[i] = str;
   actualSize++;
   ...
}
   ...
String[] actualTeams = new String[actualSize];
System.arraycopy(array, 0, actualTeams, 0, actualSize);

A better way is of course using a structure that adjusts automatically its size such as an ArrayList.

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

Comments

1

You just need to tell your stream what elements to include. You can change the line constructing the stream:

   if(str.equals("stop")) {
      //stream is called with a beginning and an end indexes.
      Arrays.stream(teams, 0, i).forEach(System.out::println);
   }

Comments

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.