簡體   English   中英

Java:打印數組中數字的 position

[英]Java: Printing the position of a number in Array

我正在編寫一個程序來打印 X position 中的數字(使用數組)。 問題是,如果我輸入的 position 大於數字序列(它在我輸入 -1 時結束)。

比如我想打印position 7中的數字,這是數字的序列:

1 2 3 -1

我應該收到一條消息說“位置不正確”,因為 position 7 中有一個 0。

否則,如果 position 7 有數字,我將打印 position 和數字。

我的問題有點奇怪,因為第一個序列讀得很好,它打印了正確的句子,但是如果我繼續輸入,它總是會讀取我使用的最后一個序列的 position,所以這不是很有用。 我附上練習的描述

編寫一個程序,給定幾個測試用例,每個測試用例由 integer 數字 i 和自然數序列 x1、x2、...、xn 組成,打印每個 xi。

輸入

輸入有幾種情況。 每個案例都以 integer 數字 i 開頭,后跟以 -1 結尾的序列 x1,...,xn。

Output

對於每種情況,如果 position i 正確,則打印 i 的內容,如示例中所示。 否則,打印“不正確的 position.”。

Scanner sc = new Scanner(System.in);
int pos;
int [] seq = new int [20];
int i;
int count = 0;


while (true) {
    pos = sc.nextInt();
    for(i = 1; i < seq.length; i++) {
        seq[i] = sc.nextInt();
            if (seq[i] == -1) {
                break;
            }               
        count++;
    }
    if (pos > count) {
        System.out.println("Posicio incorrecta" + ".");
    } else {
        System.out.println("A la posicio " + pos + " hi ha un " + seq[pos] + ".");
    }           
}       
//  hint:look at count in your code else its better to determine the scope of variables. You can uncomment the sysout line to understand better. happycoding :)
 while (true) {
            int pos;
            int i;
            int count = 0;
            int [] seq = new int [20];
            pos = sc.nextInt();
            for(i = 1; i < seq.length; i++) {
                seq[i] = sc.nextInt();
                if (seq[i] == -1) {
                    break;
                }
                count++;
            }
            //System.out.println(pos + " "+ count);
            if (pos > count) {
                System.out.println("Posicio incorrecta" + ".");
            } else {
                System.out.println("A la posicio " + pos + " hi ha un " + seq[pos] + ".");
            }
            // for(i = 1; i < seq.length; i++)
            //System.out.print(seq[i]+" ");
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM