java - 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] + ".");
}
}
解决方案
// 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]+" ");
}
推荐阅读
- python-3.x - 在破折号下拉列表中加载 100k 值
- html - Bootstrap Carousel - 模糊的静态文本框
- git - Sourcetree在结帐后立即显示文件已修改?
- python - 特定日期的 axvline - 每周数据
- c++ - 如何调整 cv::Mat 的大小以便将其用于 Qlabel(我的程序抛出 SIGSEV)
- java - 如何在管道执行期间保存或更新 Gitlab 存储库中的 excel 文件
- python - TypeError: sort_values() 得到了一个意外的关键字参数“desending”
- javascript - Expo + React Native:在两种视图的坐标之间画线
- loops - Ansible:在 Jinja 循环中构建字符串
- javascript - jQuery/JS 数字计数动画从零到值