Home > Net >  Print certain values (given by scanner) of an array in java
Print certain values (given by scanner) of an array in java

Time:11-15

I'll leave the exercise description because it is pretty clear.

"The given code reads the non-negative integer n. Initialize the short array pos of size n and read the corresponding number of values (from console) into the array. Further initialize the char array alphabet and fill it in a loop with the upper case letters from 'A' - 'Z'. Finally, loop through the array pos and output the character from the alphabet array that is in the position specified by the current value in pos. For example, if pos[i] contains the value 3, alphabet[3] should be output."

There is also a table I link here of the expected outputs.


import java.util.Scanner;
public class Exercise {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        short[] pos;
        char[] alphabet;
        pos = new short[n];
alphabet = new char[]{'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'};

for (int i = 0; i < pos.length; i  ) System.out.print(alphabet[n]);
      }
}

This code outputs the correct length of the word, but if the input is e.g. 2, it outputs "CC", which means that it only takes the first input and not the other ones.

CodePudding user response:

You need to fill your array with values and traverse through the array and print the corresponding alphabets of the position.

for (int i = 0; i < pos.length; i  ) {
            
    pos[i] = in.nextShort();

    for (int i: pos)   
        System.out.print(alphabet[i]);
}
  • Related