How to use an existing variable as a counter

0

My goal is to get the alphabet letter that the user typed in and show, how many times he typed, the letters that preceded him and his successors, do you understand? Here's what I did:

static int v;
static String[] Alfa = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
        "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

public static void main(String[] args) {
    String letra;
    Scanner s = new Scanner(System.in);

    System.out.print("Digite uma letra: ");
    letra = s.nextLine();
    System.out.print("Quantas letras deseja mostrar?");
    v = s.nextInt();

    for(int i = 1; i < Alfa.length; i++) {
        if(letra == Alfa[i]) {
            for(int i; i <= 1;) {
                System.out.print(Alfa[i--] + " ");
            }

            System.out.print(Alfa[i]);

            for(int i; i <= v;) {
                System.out.print(" " + Alfa[i++]);
            }
        }
    }
}  

It turns out that I have to use the value of Alpha [i] that is inside the if for's, but how do I do that?

    
asked by anonymous 15.10.2016 / 03:59

2 answers

2

It may be interesting to do an error handling in case the user enters a value that goes beyond the size of the String, for example choose the letter Y and display 20 elements. I did not do this because it was not mentioned. In general it would look like this:

public static void main(String[] args) {
    String letra;
    Scanner s = new Scanner(System.in);

    System.out.print("Digite uma letra: ");
    letra = s.nextLine();
    System.out.println(letra);
    System.out.print("Quantas letras deseja mostrar?");
    v = s.nextInt();

    for(int i = 0; i < Alfa.length; i++) {
        if(letra.equals(Alfa[i])) {
            for(int j = v; j > 0; j--) {
                System.out.print(Alfa[i-j] + " ");

            }

            System.out.print(Alfa[i]);

            for(int j = 1; j <= v; j++) {
                System.out.print(" " + Alfa[i+j]);
            }
        }
    }
}

Example input:

D
2

Output:

B C D E F
    
15.10.2016 / 04:43
0

As I suggested in the comment:

static int v;
static String[] Alfa = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
        "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

public static void main(String[] args) {
    String letra;
    Scanner s = new Scanner(System.in);

    System.out.print("Digite uma letra: ");
    letra = s.nextLine();
    System.out.print("Quantas letras deseja mostrar?");
    v = s.nextInt();

    for(int i = 0; i < Alfa.length; i++) {
        if(letra == Alfa[i]) {
            break;
        }
    }

    for(int j = 1; j <= i; j++) {
        if (i+j < Alfa.length) {
            System.out.print(Alfa[i+j] + " ");
        }
        if (i-j >= 0) {
            System.out.print(Alfa[i-j] + " ");
        }
    }
}  
    
15.10.2016 / 04:12