首页 > 解决方案 > Java:打印数组中数字的位置

问题描述

我正在编写一个在 X 位置打印数字的程序(使用数组)。问题是,如果我输入的位置大于数字序列(它在我输入-1时结束)。

比如我想打印位置 7 的数字,这是数字的序列:

1 2 3 -1

我应该收到一条消息,上面写着“位置不正确”,因为位置 7 有一个 0。

否则,如果位置 7 有数字,我将打印位置和数字。

我的问题有点奇怪,因为第一个序列读得很好,它打印出正确的句子,但是如果我继续输入,它总是会读取我使用的最后一个序列的位置,所以这不是很有用。我附上练习的描述

编写一个程序,给定几个测试用例,每个测试用例由整数 i 和自然数序列 x1、x2、...、xn 组成,打印每个 xi。

输入

输入有几种情况。每种情况都以整数 i 开头,后跟以 -1 结尾的序列 x1、...、xn。

输出

对于每种情况,如果位置 i 正确,则打印 i 的内容,如示例中所示。否则,打印“位置不正确。”。

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

标签: javaarraysloopsjava.util.scanner

解决方案


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

推荐阅读