Lendo um arquivo .txt em Java

5 respostas
P

Galera,

Procurei bastante no forum sobre esse assunto e todos os topicos que encontrei não me ajudaram pois meu problema é mais específico e possui objetivos diferentes.

Bom o que eu quero fazer é ler um arquivo .txt em java, character por character. O arquivo é esse (http://www.cs.montana.edu/paxton/classes/spring-2013/csci111/programs/program6/puzzle.txt).

Se notarem, as duas primeiras posições da primeira linha é o número de linhas e o número de colunas do arquivo. A princípio o que eu é apenas pegar esses dois valores (10 e 10) e declarar um array de 2 dimensões com esses valores.

Não estou conseguindo, ao invez de o array ser inicializar com [10][10] ele inicializa com [49][48], voces sabem oq pde esta acontecendo? O projeto cmpleto cnsiste de um caça palavras. :slight_smile: Segue o codigo…

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class WordFind
{
    private char [][] grid;      // the grid of letters
    
    public boolean buildGrid(String fileName)
    {
        String line;
        try
        {
            Scanner file;
            file = new Scanner (new File (fileName));
            line = file.nextLine();
            int rows = (int)line.charAt(0);
            int columns = (int) line.charAt(1);
            grid = new char[rows][columns];
            System.out.println("the size is "+rows+" and " +columns);
            return true;
        }
        catch (FileNotFoundException exception)
        {
            return false;
        }
    }
}

5 Respostas

E

Rapaz, cast não é conversão.

Você vai ter de pegar um terço e para cada conta do terço vai ter de dizer “cast não é conversão”. Reze três terços completos.

No seu caso, você deve trocar este código:

Scanner file;  
            file = new Scanner (new File (fileName));  
            line = file.nextLine();  
            int rows = (int)line.charAt(0);  
            int columns = (int) line.charAt(1);

por este:

Scanner file;  
            file = new Scanner (new File (fileName));  
            int rows = file.nextInt();
            int columns = file.nextInt();
P

Funcionou perfeitamente… Agora vou so pegar cada caracter do arquivo e colocar no array… Mas cara me diz, para que serve o cast então se não para fazer o que estava tentando? Jurava que ia converter aquela joça em int. hehe

tmvolpato

server para isso mas não dessa maneira que vc tentou fazer
de uma olhada rapida nesse link

serve para isso http://www.devmedia.com.br/aprendendo-sobre-casting-para-scjp/8319

P

Cara, muito bom esse link que voce citou, tirou várias das minhas dúvidas…

Voltando para o meu programa, agora eu teria que pegar cada character do arquivo e colocar no meu array 2d.

Eu sei que com esse código

for (int row = 0; row < grid.length; row++)
                    {
                        for (int col = 0; col < grid[0].length; col++)
                        {
                            grid[row][col] = ????
                        }
                    }

eu pecorro todo o meu array de duas dimensões e coloco algo em cada posição. O problema é que também tenho que pecorrer meu arquivo linha por linha e não sei como pecorrer o array e o arquivo ao mesmo tempo, me embolo todo com os for’s…

Para pecorrer o file eu estava fazendo

while (file.hasNextLine())
        {
            line = file.nextLine();
            for (int i = 0; i < line.length(); i++)
            {
                grid[line.charAt(i) = ????;
            }
        }

Esse método lineLength também me dar dor de cabeça, por que ele diz que o comprimento da linha é 19, mas o certo é 10… ele também conta os espaços em branco…

Voces tem alguma ideia de como popular o meu array de duas dimensoes com os caracteres do arquivo galera?

P

O dia todo nessa programa e até que enfim consegui terminar… Aqui vai o codigo do driver galera e o prgrama em si galera… [caça-palavras]

import java.util.Scanner;

public class Driver
{
    public static void main (String [] args)
    {
        WordFind game = new WordFind();
        Scanner in = new Scanner(System.in);
        String fileName;
        String word = "";
        
        System.out.println("Program 6: Word Find");
        System.out.println("--------------------\n");
        
        System.out.print("Please enter the file name > ");
        fileName = in.next();
        
        while(!game.buildGrid(fileName))
        {
            System.out.println("Error: that file does not exist.");
            System.out.print("Please enter a different file name > ");
            fileName = in.next();
        }
        
        System.out.println("\nThe grid being searched:\n");
        System.out.println(game);
        
        System.out.print("Enter a word to seek > ");
        word = in.next();
        
        while (!word.equals("quit"))
        {
            game.find(word);
            System.out.print("Enter a word to seek > ");
            word = in.next();
        }
        
        System.out.println("Goodbye!");
        
    }
}

Aqui é o codigo da classe para achar as palavras galera…

/**
 * This class allows a game of WordFind to be created and words to be sought.
 * 
 * @author Kaio Jonathas
 * @version April 25, 2013
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class WordFind
{
    private char [][] grid;      // the grid of letters
    
    public boolean buildGrid(String fileName)
    {
        String line;
        try
        {
            Scanner file;
            file = new Scanner (new File (fileName));
            int rows = file.nextInt();
            int columns = file.nextInt();
            grid = new char[rows][columns]; 
            
            line = file.nextLine();
            for (int row = 0; row < grid.length; row++)
            {
                line = file.nextLine();
                for (int col = 0; col < grid[0].length; col++)
                {
                     grid[row][col] = line.charAt(col*2);
                }
            }
            return true;
        }
        catch (FileNotFoundException exception)
        {
            return false;
        }
    }
    
    public String toString()
    {
        String result = "      1  2  3  4  5  6  7  8  9 10\n"+"   "+lineSeparator()+"\n";
        int i = 1;
        for (int row = 0; row < grid.length; row++)
        {   
            if(i!=10)
            {
                result = result + i++ +"  |";
            }
            else
            {
                result = result + i++ +" |";
            }
            for (int col = 0; col < grid[0].length; col++)
            {
                result = result + "  " +grid[row][col];
            }
            result = result + "\n";
        }
        return result;
    }
    
    private String lineSeparator()
    {
        String result = "";
        
        for (int i = 0; i < grid[0].length+1; i++)
        {
            if(i == 0)
            {
                result += "+";
            }
            else
            {
                result += "---";
            }
        }
        return result;
    }
    
    public void find(String word)
    {
        int n = 0; //Number of occurences in a specific position
        int nTotal = 0; //Total number of occurrences
         for (int row = 0; row < grid.length; row++)
            {
                for (int col = 0; col < grid[0].length; col++)
                {
                    n = 0; // Clearing n to start counting again in another position
                    if(grid[row][col] == word.charAt(0))
                    {
                        if(lookInDirections(0,word,row,col,1))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,2))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,3))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,4))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,5))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,6))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,7))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                        if(lookInDirections(0,word,row,col,8))
                        {
                            n = n+1;
                            nTotal = nTotal +1;
                        }
                    }
                    if(n>0)
                    {
                        System.out.println("... found "+ n +" occurrence(s) at row "+ (row+1) +", column " + (col+1));
                    }
                }
            }
        System.out.println("Found " +nTotal+ " total occurrences.\n");
    }
    //1 - North
    //2 - Northeast
    //3 - East
    //4 - Southeast
    //5 - South
    //6 - Southwest
    //7 - West
    //8 - Northwest
    private boolean lookInDirections(int index, String word, int x, int y, int direction)
    {
        if(direction == 1)//if direction is north I just have to worry about x because we are not changing y
        {   
            if(word.length()==1)
            {
                return true;
            }
            else if (index+1 == word.length())
            {
                return true;
            }
            if(x>0)
            {
                if(grid[x-1][y] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x-1, y, 1); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 2)
        {
            if(word.length()==1)
            {
                return false; //because I have already returned true above and if I return true again it will count a letter 8 times, like if it was in the 8 directions
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(x>0 && y<grid[0].length-1)
            {
                if(grid[x-1][y+1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x-1, y+1, 2); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 3)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(y<grid[0].length-1)
            {
                if(grid[x][y+1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x, y+1, 3); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 4)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(x<grid[0].length-1 && y<grid[0].length-1)
            {
                if(grid[x+1][y+1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x+1, y+1, 4); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 5)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(x<grid[0].length-1)
            {
                if(grid[x+1][y] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x+1, y, 5); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 6)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(y>0 && x<grid[0].length-1)
            {
                if(grid[x+1][y-1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x+1, y-1, 6); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 7)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(y>0)
            {
                if(grid[x][y-1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x, y-1, 7); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        
        if(direction == 8)
        {
            if(word.length()==1)
            {
                return false;
            }
            if(index+1 == word.length())
            {
                return true;
            }
            if(y>0 && x>0)
            {
                if(grid[x-1][y-1] == word.charAt(index+1))
                {
                    return lookInDirections(index+1, word, x-1, y-1, 8); //I have to take care of the bounds
                }
                else
                {
                    return false;
                }
            }
        }
        return false;
    }
}
Criado 23 de abril de 2013
Ultima resposta 24 de abr. de 2013
Respostas 5
Participantes 3