[英]Searching an array with user input and printing all elements that have this value
我正在嘗試在一個數組中搜索某個值,並在 java 中顯示包含該值的所有元素。例如,用戶選擇數字 5,數組中存儲了 3 個具有該值的項目,因此所有 3 個項目將被打印出來。 我的代碼編譯正常,但是當我運行它時,它會跳轉到 else 語句,即使我輸入的是數組中的數字。任何幫助都會很棒。 這是我的代碼:
case 3:
//display all elements with the same state
//get number user wishes to search for
boolean found = false;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number you wish to search for");
//read user input
num = input.nextInt();
//traverse array
int k = 0;
for(k=0; k < myMonths.length; k++){
if(myMonths[index] == num){
found = true;
break;}
if(found){System.out.println(k);}
else{System.out.println("not found");}
}
break;
這是數組:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
//int n = number of projects
int n = 1;
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;} }
break;
首先,您應該使用k
而不是index
。 其次,您不應該在每次迭代時都打印“未找到”(或對此進行測試)。 您應該盡可能地限制變量 scope。 你還提到想要找到所有匹配的索引,所以你不應該過早地終止循環; 我想你想要類似的東西
//assume the value isn't present.
boolean found = false;
//read user input
int num = input.nextInt();
//traverse array
for(int k = 0; k < myMonths.length; k++) {
if (myMonths[k] == num){
found = true;
System.out.println(k); // don't break or the loop ends early.
}
}
//this test can only be done after you iterate **all** values.
if (!found) {
System.out.println("not found");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.