简体   繁体   中英

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

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 eg 2, it outputs "CC", which means that it only takes the first input and not the other ones.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM