display on the screen the contents of the position?

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



public class Trabalho {

    public static void main(String[] args) throws FileNotFoundException {
        int qtd = 0;
        int ler;
         String x[] = new String[5];

        try {
            BufferedReader lerArq = new BufferedReader(new FileReader("entrada.txt"));  

            String linha = lerArq.readLine(); 

            while (linha != null) {
                System.out.printf("%s\n", linha);
                x[qtd] = linha;
                qtd++ ;
                linha = lerArq.readLine();
            }


        } catch (IOException e) {
            System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
        }

System.out.println();

int n, i,  troca;
        String aux;



        n = 1;
        troca = 1;

        while (n <= 5 && troca == 1) {
            troca = 0;
            for (i = 0; i <= 3; i++) {   
                if (x[i].compareTo(x[i + 1]) > 0) {
                    troca = 1;
                    aux = x[i];
                    x[i] = x[i + 1];
                    x[i + 1] = aux;
                    PrintStream ps = new PrintStream("entrada-ord.txt");
               for (i = 0;i <= 4; i++) {
             ps.println(x[i]);
               }
                }

            }
            n = n + 1;

        }
        for (i = 0; i <= 4; i++) {
            System.out.println(x[i]);


        }




    }
}

I made this code that it took a file of 5 vectors (String) ordered and made a txt file with the ordered files, and now I would like me to type a number and print on the screen the string of my vector that is stored in the number I typed.

Scanner sc = new Scanner(System.in);
        System.out.println("Qual linha voce quer ver o conteudo?");
        ler = sc.nextInt();

        for ( i = 0; i < x.length; i++) {
            if (String.valueOf( ler ).equals( x[i] ) ) {

                System.out.println(x[i]);
            }
        }

I tried this but it is not

    
asked by anonymous 20.11.2014 / 23:02

1 answer

1

You have a logic error when submitting the space that the user chooses:

First, but without affecting much, is that you are giving a scanner.nextInt () even when the user types something that is not Integer, or is outside the limits of an Integer.

Second, and the main one: Here: if (String.valueOf( ler ).equals( x[i] ) ) , you check if the value entered equals some value within x while you should check the reference, not the content.

As it seems to me that you want, it is simply to do:

System.out.println(x[ler-1]);
//Lembrando aqui que o armazenamento do vetor começa com 0, e vai até 'length-1'.

Because ler will have the reference that the user wants to see.

    
21.11.2014 / 11:25