英文:
Index of number(s) in list in JAVA
问题
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("Search for? ");
int src = scanner.nextInt();
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
if (src == num) {
System.out.println(src + " is at index " + i);
}
}
}
}
英文:
I need to have a program that asks the user for a number, and reports that number's index in the list. If the number is not found, the program should not print anything.
Example:
Sample Output:
1
2
3
3
4
Search for? 3
3 is at index 2
3 is at index 3
This is what I have written but the put is looping multiple times. Can you suggest fixing it?
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == -1) {
break;
}
list.add(input);
}
System.out.println("Search for? ");
int src = scanner.nextInt();
int ind = 0;
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = list.indexOf(src);
}
System.out.println(src + " is at index " + ind);
}
}
}
EDIT
> Input: 1 2 3 3 4 -1
>
> Search for? 3 Output: 3 is at index 0 3 is at index 0 3 is at index 2 3 is at index 2 3 is at index 2 ///So it must be only one sentence for each index. Even if I put after "for" loop, it only output the first if index.
答案1
得分: 0
我能看到你代码中的一个问题,即你打印了所有的内容,而不仅仅是匹配的部分。为了解决这个问题,你需要将System.out.println
放到if
语句中,就像这样:
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = i;
System.out.println(src + " 在索引 " + ind);
}
}
如果还有其他问题,请告诉我。
英文:
I can see a single problem in your code, that is, you print everything, not only the matches. To solve that you need to put your System.out.println
into the if
, like this:
for(int i=0; i<list.size(); i++){
int num = list.get(i);
if(src == num){
ind = i;
System.out.println(src + " is at index " + ind);
}
}
Let me know if anything else was wrong.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论