Reading strings and saving them in arrays

-1

I'm trying to make a program where salesperson names have to be read and have to be stored in an array.

My biggest problem is that I do not know what the limit of names entered by the user is. So I used the while:

public static void main(String[] args)
{
  Scanner ler = new Scanner(System.in);
  String seller = "";
  int x = 0;
  String[] arr = new String[x];
  
  while (!vendedor.equals("end"))
  {
    System.out.print("Vendedor: ");
    vendedor = ler.next();
    
    for (int indice = 0; indice < arr.length; indice++)
    {
      arr[indice] = ler.next();
      System.out.print(arr[indice]);

    }
  }
}

Thank you!

    
asked by anonymous 31.12.2018 / 16:50

2 answers

2

I'll leave my contribution more as an alternative because we do not know if your teacher will accept the trick with split() .

I used your idea to impose a limit based on the size of the array.

So let's say you create, for example, an array with size 10.

If you enter only 5 names, in the end it prints only the 5 names.

If you insert 10, which is the limit in the example, the loop automatically stops and prints the 10 names.

Then I got there:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner ler = new Scanner(System.in);
    int tamanho = 3;
    int indice = 0;
    String[] arr = new String[tamanho];

    while (indice != tamanho)  {
      System.out.print("Vendedor: ");
      String vendedor = ler.nextLine();

      if (vendedor.equals("end")) break;

      arr[indice++] = vendedor;
    }

    for (int i = 0; i < indice; i++)
      System.out.println(arr[i]);
  }
}
    
01.01.2019 / 07:43
0

@Wilherme Daniel

Get everything before and after it goes to your array.

public class StackOverflow {

    public static String EXIT = "exit";

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in);
        StringBuilder bancoDeDados = new  StringBuilder(); 

        while (ler.hasNext()) {

            String str = ler.next();
            bancoDeDados.append(str + ",");         
            if(str.contains(EXIT)) break;           
        }

        int tamanhoDoArray = bancoDeDados.toString().split(",").length;
        String[] arr = new String[tamanhoDoArray];
        arr = bancoDeDados.toString().split(",");
    }
}
    
31.12.2018 / 21:15