How to create an array whose indices are characters from an informed string?

Asked

Viewed 340 times

5

I wanted to create a vector in java in which each input of the vector was a character of a string that I informed

public static void main(String[] args) { 

    String[] words = {"java"};

    System.out.println("\n"+words[3]);  //para dar um print na letra"a"

}
  • Could you properly format your code? Just select it and type ctrl + k

  • Okay, I just wanted to make this vector receive a string and I could separate each character of it into a vector index, I don’t know if it was clear

2 answers

5

No need to transform into array, just call the method charAt() by passing the position of the letter as String is a Charsequence, that is, a sequence of characters that can be captured using the above method.

String word = "java";

System.out.println("\n"+ word.charAt(3));  

See working on ideone.

Obs.: it is always good to check if the last Dice is smaller than the string size by checking seuIndice < palavra.length because if the Dice passed to this method is larger than the string size, an exception will be made IndexOutOfBoundsException.

Remembering that a word’s input starts from 0 to the size of the String -1.

But if even with all this ease provided by the language you want to insist on creating array, it is also possible to convert a String into an array of char, with the method toCharArray():

char[] words = "java".toCharArray();
System.out.println("\n"+words[3]);

See also working on IDEONE.

3

Try it this way:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Teste {

    public static void main(String[] args) {

        /**
         * Vamos utilizar para ler as informações do console...
         */
        BufferedReader buffReader = null;
        try {
            /**
             * Criamos uma instancia do fluxo de entrada padrão. Esse fluxo já está aberto e
             * pronto para fornecer dados de entrada. Este fluxo corresponde à entrada do
             * teclado (normalmente) do usuário.
             */
            buffReader = new BufferedReader(new InputStreamReader(System.in));

            while (true) { // irá permanecer nesta iteração, até que o usuário digite sair!

                // pedimos ao usuário uma palavra
                System.out.print("\nDigite\n: ");

                /**
                 * Aguarda o usuário digitar, e quando aperta ENTER, a String input recebe as
                 * informações. Sem incluir nenhum caractere de terminação de linha, ou nulo se
                 * o final do fluxo foi atingido.
                 */
                final String input = buffReader.readLine();

                // compara as String´s ignorando Maisculas e minusculas!
                if ("sair".equalsIgnoreCase(input)) { 
                    System.out.println("Você saiu da aplicação!");
                    // Sai da aplicação
                    System.exit(0); 
                } else {
                    System.out.printf("Você digitou %d letras\n", input.length());
                    // Vamos iterar os carateres!!!
                    final char[] caracteres = input.toCharArray(); 
                    for(int i =0; i < caracteres.length; i++) {
                        System.out.printf("Posição: %d, caracter: %c\n", i, caracteres[i]);
                    }

                }

            }
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (buffReader != null) {
                try {
                    buffReader.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.