Simplify.
In this example the least manual way is not to do this assignment for these variables. They are not being used and even if they are used in a continuation of the code, why? Use the vector variables themselves.
If you have to create the variables yourself, declare the attribute at once.
Variables are memory storage locations with a name, nothing more than this. Why store a value somewhere with a name? Usually because you need to use it more than once. Or if you need to do several steps with that value that cannot be put together. It can also be when you’re doing something very complex and you want to document it better, but that’s less common.
Why create variables without need? Whenever you cannot explain why a variable exists, delete it. This basic "rule" already helps. Of course one can still give meaningless explanations.
The simplified code that does the same thing (the code didn’t even compile in written form):
class Teste30 {
public static void main(String[] args) {
for (String nome : "Isso funciona mesmo, ok?".split(" ")) System.out.println(nome);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
But if you still want to create these loose variables for later use:
class Teste30 {
public static void main(String[] args) {
String teste = "Isso funciona mesmo, ok?";
String[] vetor = teste.split(" ");
String aqui = vetor[0];
String ali = vetor[1];
String acola = vetor[3];
String there = vetor[4];
for (String nome : vetor) System.out.println(nome);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
But because you don’t like that shape?
– LocalHost
To answer if you have a less manual form, it depends a lot on what you want to do. Your code for example does not make clear what was the reason why it was broken so, since
aqui
,ali
,acola
andthere
are not used anywhere. Also, this code does not compile, as there is an extra key lock (orfor
just went out of method) and also,testelista
is not stated anywhere. Explain better what you want to do with theString
s obtained from thesplit(" ")
, that it will give to answer something.– Victor Stafusa
Out of curiosity, why not use them from within the vector already generated accessing through the indexes?
– Wilker
Also, take a look at XY problem, because I think your question is a case of this problem (although I may be wrong).
– Victor Stafusa
@Wilker sin verdade I will do this way as you quoted. Thank you very much
– Aline
I don’t know @Localhost is going to have a better way to write that code. Imagine that I need to break String and the result is to save 40 positions in an array. To use these values, just use directly by the same array?
– Aline
That’s right. You can access directly from the array index.
– Wilker
I got it... OK! I’m gonna lay it out like this.
– Aline
If it were PHP, you could use "Extract", but in java, or any other compiled language, there is nothing similar.
– mau humor