Gostaria de saber se alguém poderia me ajudar neste caso:
Tenho um arquivo TXT da seguinte forma:
COR PREFERIDA ; AZUL ; AMARELO ; VERMELHO ; VERDE
MARCA DO VEICULO ; VW ; FIAT ; GM ; KIA ; FORD ; BMW ; RENAULT
Com a classe abaixo eu consigo através do split colocar os elementos na ARRAY data[],
porem cada linha do arquivo tem o numero de elementos que varia, queria saber como faço para colocar
as pergunta numa array PERGUNTA[] e as respostas num array RESPOSTAS[] varrendo todo o arquivo
utilizando este exemplo abaixo.
public static void main(String[] args){
try {
/String filePath = “c:/temp/QUEST.txt”;
BufferedReader in = new BufferedReader(new FileReader(filePath));
String str;
while ((str = in.readLine()) != null) {
String data[] = str.split(";");
System.out.println(“PERGUNTA " + data[0] + " RESPOSTA:” + data[1]);///
No lugar do split, eu acho que seria melhor utilizar o StringTokenizer…
StringTokenizer st = new StringTokenizer(str, ";");
String pergunta = st.nextToken();
int i = 0;
String respostas[] = new String[st.countTokens()-1];
while(st.hasMoreTokens()){
respostas[i++] = st.nextToken();
}
E acho que vc deveria utilizar outra estrutura no lugar de um array…
Você quer colocar as respostas de todas as perguntas em um único array??
Não entendi direito…
Acho que seria melhor se você tivesse um List com as perguntas e um List<String[]> com as respostas.
tipo:
List<String> perguntas = new ArrayList<String>();
List<String[]> respostas = new ArrayList<String[]>();
Ou ainda melhor seria
List<String> perguntas = new ArrayList<String>();
List<List<String>> respostas = new ArrayList<<List<String>>();
e depois
BufferedReader in = new BufferedReader(new FileReader(filePath));
String str;
List<String> l = new ArrayList<String>(); //Declara a lista que recebe as perguntas de cada resposta
while ((str = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(str, ";"); //Divide a string a cada ";"
perguntas.add(st.nextToken()); //A pergunta é sempre o primeiro token
l = new ArrayList<String>(); //"Reinicia" o ArrayList
while(st.hasMoreTokens()){ //hasMoreTokens verifica se ainda tem elementos
l.add(st.nextToken()); //Adiciona as respostas no ArrayList
}
respostas.add(l); //Adiciona as respostas no ArrayList respostas
}
Desejo colocar as Perguntas numa ArrayList e as respostas em outra.
Não querendo abusar da sua paciência, sou novato em Java, e estou testando
os exemplos que você colocou, fui compilar agora este que você separa as
perguntas e respostas, e ele informa 3 erros:
List l = new List(); //Declara a lista que recebe as perguntas de cada resposta
“java.util.List is abstract; cannot be instatiated”
l = new List(); //“Reinicia” o ArrayList
“java.util.List is abstract; cannot be instatiated”
respostas.add(l); //Adiciona as respostas no ArrayList respostas
“cannot find symbol”
//respostas.add(l); //Adiciona as respostas no ArrayList respostas
não funcionou, alterei da forma que está aí embaixo, e queria testar pra ver se as perguntas e respostas
foram para seus devidos arrays, coloquei umas linhas la embaixo, mas não consegui visualizar.
Desculpe(em) minha falta de experiência, e obrigado até o momento pela ajuda e pelas dicas.
String filePath = “c:/temp/QUEST.txt”;
List perguntas = new ArrayList();
List respostas = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader(filePath));
String str;
//List l = new List(); //Declara a lista que recebe as perguntas de cada resposta
List l = new ArrayList(); //Declara a lista que recebe as perguntas de cada resposta
while ((str = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(str, “;”); //Divide a string a cada “;”
perguntas.add(st.nextToken()); //A pergunta é sempre o primeiro token
//l = new ArrayList<String>();
while(st.hasMoreTokens()){ //hasMoreTokens verifica se ainda tem elementos
//l.add(st.nextToken()); //Adiciona as respostas no ArrayList
respostas.add(st.nextToken());
}
//respostas.add(l); //Adiciona as respostas no ArrayList respostas
for (int i = 0; i < perguntas.length; i++) {
System.out.println("\t "+ perguntas[i]);
}
}
public static void main(String[] args){
List<String> perguntas = new ArrayList<String>();
List<List<String>> respostas = new ArrayList<List<String>>();
try {
String filePath = "c:/Temp/QUEST.txt";
BufferedReader in = new BufferedReader(new FileReader(filePath));
String str;
List<String> l = new ArrayList<String>(); // Declara a lista que recebe as perguntas de cada resposta
while ((str = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(str, ";"); // Divide a string a cada ";"
perguntas.add(st.nextToken()); // A pergunta é sempre o primeiro token
l = new ArrayList<String>();
while (st.hasMoreTokens()) { // hasMoreTokens verifica se ainda tem elementos
l.add(st.nextToken()); // Adiciona as respostas no ArrayList
}
// Aqui todas as respostas da pergunta atual vão estar em l
// Adiciona l ao ArrayList respostas
respostas.add(l);
}
} catch (Exception e) {
System.out.println("Lançou excessão!!! " + e.getMessage());
e.printStackTrace();
}
//Imprime as perguntas/respostas
int j = 0;
for(String p : perguntas) {
System.out.println("Pergunta: "+p);
System.out.println("Respostas: ");
for(String r : respostas.get(j)) {
System.out.println("\t -"+r);
}
j++; //Passa para as respostas da proxima pergunta
System.out.println();
}
}