show on the screen the position content?

Asked

Viewed 423 times

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 he took a file of 5 vectors (String) ordered and made a txt file with the ordered files, and now I would like that I type a number and would print on the screen the string of my vector that is stored in the number that 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 that but it’s not

1 answer

1


There is a logic error when presenting the space the user chooses:

First, but without affecting much, is that you are giving a scanner.nextInt() even when the user type 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] ) ), vc checks if the entered value is equivalent to some value within x while you should check the reference, not the content.

The way it seems to me you want, is to just do:

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

For ler will have the reference that the user wants to view.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.