Leitura de um arquivo e armazenamento em um vetor

2 respostas
K

Hi Guys,
Preciso fazer um trabalho pra faculdade, trata-se de um programa que receba dados internos e externos e os armazene em vetores para serem ordenados, e tem de apresentar o tempo que levou a ordenação. O código atualmente está assim:

import java.text.DecimalFormat;


import java.util.concurrent.TimeUnit;

import javax.swing.JOptionPane;


public class Org666 {

	public static int[]ivetorBS = new int[10];
	public static int[]ivetorMS = new int[10];
	public static int[]ivetorQS = new int[10];
	public static String[]vetorMS = new String[10];
	
	
	
	public static int[] BS (int[] ivetorBS ){
		
        int aux = 0;
        int i = 0;
        
        System.out.println(" ");
        for (i = 0; i < ivetorBS.length; i++) {
            for (int j = 0; j < ivetorMS.length - 1; j++) {
                if (ivetorBS[j] > ivetorBS[j + 1]) {
                    aux = ivetorBS[j];
                    ivetorBS[j] = ivetorBS[j + 1];
                    ivetorBS[j + 1] = aux;
                }
            }
        }
        
		return ivetorBS;
		
	}
	
	static int[] MS(int[] ivetorMS) {
	    if (ivetorMS.length <= 1) {
	        return ivetorMS;
	    }
	    int meio = ivetorMS.length / 2;
	    int[] dir = ivetorMS.length % 2 == 0 ? new int[meio] : new int[meio + 1];
	    int[] esq = new int[meio];
	 
	    int[] aux = new int[ivetorMS.length];
	 
	    for (int i = 0; i < meio; i++) {
	        esq[i] = ivetorMS[i];
	    }
	 
	    int auxIndex = 0;
	    for (int i = meio; i < ivetorMS.length; i++) {
	        dir[auxIndex] = ivetorMS[i];
	        auxIndex++;
	    }
	 
	    esq = MS(esq);
	    dir = MS(dir);
	 
	    aux = mergesort(esq, dir);
	    
        
	    return aux;
	}
	 
	static int[] mergesort(int[] esq, int[] dir) {
	    int[] aux = new int[esq.length + dir.length];
	 
	    int indexDir = 0, indexEsq = 0, indexAux = 0;
	 
	    while (indexEsq < esq.length || indexDir < dir.length) {
	        if (indexEsq < esq.length && indexDir < dir.length) {
	            if (esq[indexEsq] <= dir[indexDir]) {
	                aux[indexAux] = esq[indexEsq];
	                indexAux++;
	                indexEsq++;
	            } else {
	                aux[indexAux] = dir[indexDir];
	                indexAux++;
	                indexDir++;
	            }
	        } else if (indexEsq < esq.length) {
	            aux[indexAux] = esq[indexEsq];
	            indexAux++;
	            indexEsq++;
	        } else if (indexDir < dir.length) {
	            aux[indexAux] = dir[indexDir];
	            indexAux++;
	            indexDir++;
	        }
	    }
	    return aux;
	}
	public static void QS(int[] ivetorQS) {
        
		 
        quick_sort(ivetorQS,0, ivetorQS.length - 1);
        
    }
 
    
    
 
    public static void quick_sort(int[] v, int ini, int fim) {
        int meio;
 
        if (ini < fim) {
            meio = partition(v, ini, fim);
            quick_sort(v, ini, meio);
            quick_sort(v, meio + 1, fim);
        }
    }
 
    public static int partition(int[] v, int ini, int fim) {
        int pivo, topo, i;
        pivo = v[ini];
        topo = ini;
 
        for (i = ini + 1; i <= fim; i++) {
            if (v[i] < pivo) {
                v[topo] = v[i];
                v[i] = v[topo + 1];
                topo++;
            }
        }
        v[topo] = pivo;
        return topo;
    }
	
	
	
	
	
	public static void main(String[] args) {
		
		
		String op;
		int i;
		float aux;
		
		
		op = JOptionPane.showInputDialog("Escolha uma das opções:\n 1: Dados Internos\n 2: Dados Externos ");
		DecimalFormat df = new DecimalFormat("0.00");
		switch(op){
		
		case "1" :
			
			for(i=0; i < 10; i++){
				vetorMS[i] = JOptionPane.showInputDialog("Digite o "+ (i+1) + "º dado do vetor");
				ivetorMS[i] = Integer.parseInt(vetorMS[i]);
				ivetorQS[i] = ivetorMS[i];
				ivetorBS[i] = ivetorMS[i];
			}
			
			System.out.println("Dados Digitados ");
		for (i = 0; i < ivetorMS.length; i++) {
            System.out.println(" " + ivetorMS[i]);
		}
			long start = System.nanoTime(); //Marca tempo antes da execução do método
            BS(ivetorBS);
            long end = System.nanoTime(); 	//Calcula tempo gasto pelo método
            end -= start;
            end = end / 1000;
            String str = df.format(end);
            
           
            System.out.println("Vetor organizado BubbleSort:");
            for (i = 0; i < ivetorBS.length; i++) {
                System.out.println(" " + ivetorBS[i]);
                }
            System.out.println("Tempo de execução: " + str + " Microsegundos");
            start = System.nanoTime();		//Marca tempo antes da execução do método
            ivetorMS = MS(ivetorMS);
            end = System.nanoTime();		//Calcula tempo gasto pelo método
            end = end - start;
            end = end / 1000;
            str = df.format(end);
            
            System.out.println("Vetor organizado MergeSort:");
            for (i = 0; i < ivetorMS.length; i++) {
                System.out.println(" " + ivetorMS[i]);
                }
            System.out.println("Tempo de execução: " + str + " Microsegundos");
            start = System.nanoTime();		//Marca tempo antes da execução do método
            QS(ivetorQS);
            end = System.nanoTime();		//Calcula tempo gasto pelo método
            end -= start;
            end = end / 1000;
            str = df.format(end);
            
            System.out.println("Vetor organizado QuickSort:");
            for (i = 0; i < ivetorQS.length; i++) {
                System.out.println(" " + ivetorQS[i]);
            }
            System.out.println("Tempo de execução: " + str + " Microsegundos");
		
            case "2" :
            	
            	System.out.println("Dados Digitados ");
        		for (i = 0; i < ivetorMS.length; i++) {
                    System.out.println(" " + ivetorMS[i]);
        		}
        			start = System.nanoTime(); //Marca tempo antes da execução do método
                    BS(ivetorBS);
                    end = System.nanoTime(); 	//Calcula tempo gasto pelo método
                    end -= start;
                    end = end / 1000;
                    str = df.format(end);
                    
                   
                    System.out.println("Vetor organizado BubbleSort:");
                    for (i = 0; i < ivetorBS.length; i++) {
                        System.out.println(" " + ivetorBS[i]);
                        }
                    System.out.println("Tempo de execução: " + str + " Microsegundos");
                    start = System.nanoTime();		//Marca tempo antes da execução do método
                    ivetorMS = MS(ivetorMS);
                    end = System.nanoTime();		//Calcula tempo gasto pelo método
                    end = end - start;
                    end = end / 1000;
                    str = df.format(end);
                    
                    System.out.println("Vetor organizado MergeSort:");
                    for (i = 0; i < ivetorMS.length; i++) {
                        System.out.println(" " + ivetorMS[i]);
                        }
                    System.out.println("Tempo de execução: " + str + " Microsegundos");
                    start = System.nanoTime();		//Marca tempo antes da execução do método
                    QS(ivetorQS);
                    end = System.nanoTime();		//Calcula tempo gasto pelo método
                    end -= start;
                    end = end / 1000;
                    str = df.format(end);
                    
                    System.out.println("Vetor organizado QuickSort:");
                    for (i = 0; i < ivetorQS.length; i++) {
                        System.out.println(" " + ivetorQS[i]);
                    }
                    System.out.println("Tempo de execução: " + str + " Microsegundos");
        		
        	   
			}
		  
		 
        }
	
	
		
	}

Mas n sei como pegar os dados de um arquivo txt e armazenar cada linha em um vetor, se puderem me ajudar sou muito grato

2 Respostas

A

Segue abaixo o método para ler números, delimitados por vírgula, de um arquivo de texto.

Primeiro, você deve criar o arquivo de texto e inserir os números separados por vírgula (sem espaços). Depois alterar o endereço do arquivo no método. No meu caso, o arquivo eu salvei na pasta “C:\testejava\arquivo.txt”.

Falta fazer:

  1. Salvar os números em uma lista e retornar no método.
  2. Tratar o FileNotFoundException.

Uma dica, você pode abrir uma janela para o usuário selecionar o arquivo.

Você pode abrir uma janela para o usuário selecionar o arquivo.

// Exemplo do arquivo de texto
    //  12,76,82,99,6726,-982,-1,83,0,3
    public void abrirArquivo() throws FileNotFoundException {
		Scanner scanner = new Scanner(new FileReader("/testejava/arquivo.txt")).useDelimiter(",");		
		while (scanner.hasNext()) {
			Integer numero = scanner.nextInt();
			System.out.println(numero);
			
		}
	}
K

Vlw cara,
Vou criar um JOptionPane para o usuário digitar o local do arquivo salvar em uma variável e usar no lugar do endereço,
só que eu queria que ele colocasse os dados do txt em um vetor, tipo, cada um daqueles números inteiros em uma posição do vetor, vou tentar usar um for no lugar do while e colocar vetor[i] pra receber o conteudo da var numero , agora uma duvida, teria como eu ao invés
de usar um delimitador como a ‘,’ vírgula eu poderia separar os dados cada um em uma linha e fazer o scanner passar neles linha por linha ?

Agradeço a ajuda.

Criado 16 de maio de 2015
Ultima resposta 17 de mai. de 2015
Respostas 2
Participantes 2