Problemas com Scanner

3 respostas
aajjbb

o problema parece ser muito simples, mas depois de algumas horas, resolvi buscar ajuda, o seguinte codigo procura quantas vezes uma determinada letra na qual o usuario insere, aparece no arquivo xanadu.txt :

In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.

mas como o arquivo contem quebra de linhas, e meu progama so esta lendo a primera linha, so consigo procurar os caracteres dela, como conseguiria iterar sobre todos os caracteres do arquivo, nao apenas a primeira linha? segue o codigo abaixo

package br.com.teste;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class LetterTimes {

	public void countLetter() throws IOException, FileNotFoundException {
		Scanner input = null;
		Scanner input2 = new Scanner(System.in);
		
		System.out.println("Digite o Caracter que deseja procurar");
		String letra = input2.nextLine();
		
		int count = 0;

		try {
			input = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
			String xan = input.nextLine();
		while(input.hasNextLine()){	
			System.out.println(xan);
			
			if (xan.contains(letra)) {
				count++;
				System.out.println("\nLetter " + letra + " was found about " + count + " times...\nCongratulations");
				break;
			} else {
				System.out.println("\nLetter " + letra + " was did not found");
				break;
			}
		}
		
		} finally {
			if (input != null) {
				input.close();
			}
	
	}
}
	public static void main(String[] args) throws IOException {
		LetterTimes l = new LetterTimes();
			l.countLetter();
	}
}

3 Respostas

romarcio

Pode usar Regex.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class LetterTimes {

    public void countLetter() throws IOException, FileNotFoundException {
        Scanner input = null;
        Scanner input2 = new Scanner(System.in);

        System.out.println("Digite o Caracter que deseja procurar");
        String letra = input2.nextLine();

        int count = 0;

        try {
            input = new Scanner(new BufferedReader(new FileReader("saida.txt")));

            Pattern pattern = Pattern.compile(letra);      //expressao que deseja procurar
            Matcher matcher;

            while (input.hasNextLine()) {
                matcher = pattern.matcher(input.nextLine()); //a origem(linha que procura pela expressão)
                while (matcher.find()) { //faz um while na linha e sempre que encontrar a expressão, incrementa count
                    count++;
                }
            }
            if (count > 0) {
                System.out.println("\nLetter " + letra + " was found about " + count + " times...\nCongratulations");

            } else {
                System.out.println("\nLetter " + letra + " was did not found");
            }
        } finally {
            if (input != null) {
                input.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        LetterTimes l = new LetterTimes();
        l.countLetter();
    }
}

Dessa forma você pode inclusive procurar por palavras ou até por seqüências de caracteres entre palavras.

aajjbb

ahh, realmente é uma forma mais inteligente, eu estou vendo um pouco de regex no java tutorials agora, mas eles fazem muito rodeio lá, se voce conhecer uma fonte um pouco mais simples pra quem ainda nao sabe muito sobre regex e puder me passar, obrigado.

E

http://aurelio.net/er/

Criado 13 de novembro de 2010
Ultima resposta 13 de nov. de 2010
Respostas 3
Participantes 3