![](/img/trans.png)
[英]Search an Array (or ArrayList) for a specific person(value), given by scanner user and if found, return/print all values in that array to the scanner
[英]Print certain values (given by scanner) of an array in java
我將留下練習說明,因為它非常清楚。
“給定的代碼讀取非負 integer n。初始化大小為 n 的短數組 pos 並將相應數量的值(從控制台)讀入數組。進一步初始化 char 數組字母表並將其填充到循環中case letters from 'A' - 'Z'。最后,遍歷數組 pos 和 output 字母表數組中的字符,該字符在 position 中,由 pos 中的當前值指定。例如,如果 pos[i] 包含值3、alphabet[3]應該是output。”
我在此處鏈接了一張預期輸出的表格。
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]);
}
}
此代碼輸出正確的單詞長度,但如果輸入為 2,則輸出“CC”,這意味着它只接受第一個輸入而不接受其他輸入。
您需要用值填充數組並遍歷數組並打印 position 的相應字母表。
for (int i = 0; i < pos.length; i++) {
pos[i] = in.nextShort();
for (int i: pos)
System.out.print(alphabet[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.