简体   繁体   English

我将如何遍历数组以查看用户输入变量(数字)是否等于数组中的一个元素并用“@”替换该元素

[英]how would i loop through an array to see if the user input variable(number) is equal to a element in the array and replace that element with a “@”

//my array(arrayAlphabetizer) is an int[] with random int with a capacity = the users name and surname
//allow the user to enter a value from arrayAlphabetizer element to search for

Scanner value = new Scanner(System.in);
System.out.println("please enter a value from the array to search for");
String search = input.nextLine();

//change input into int
int number = Integer.parseInt(search);

//loop through the array to find the value
for (int i = number; i <= arrayAlphabetizer.length; number++) {

    if (i <= number) {
        arrayAlphabetizer[i] = 0;
        System.out.println(Arrays.toString(arrayAlphabetizer));
    } else {
        System.out.print(i);
    }
}

I've tried this and multiple other methods but nothings is working我已经尝试过这种方法和其他多种方法,但没有任何效果

You are setting i = to number at the start of your loop.您在循环开始时将 i = 设置为编号。 Your if statement will be executed in the first iteration of the loop.您的 if 语句将在循环的第一次迭代中执行。 I think you want to start your loop at i = 0. Also I needs to be less than the length of the array, not less than or equal to.我想你想从 i = 0 开始你的循环。另外我需要小于数组的长度,不小于或等于。

for(int i = 0; i < array.length; i++){
     if(array[i] == number)
          System.out.println(**whatever you want to print**);
     else
          System.out.println(**whatever you want to print);

}

You are trying to add a char into an int array which does not work.您正在尝试将 char 添加到不起作用的 int 数组中。 Are you sure you need to do that?你确定你需要这样做吗?

I hope this helps.我希望这有帮助。 Your question was a bit unclear and I cannot comment yet to ask for clarification so just respond if you have questions.你的问题有点不清楚,我还不能评论要求澄清,所以如果你有问题就回答。

int number = Integer.parseInt(search); int number = Integer.parseInt(搜索);

for (int i = 0; i <= arrayAlphabetizer.length; number++) { for (int i = 0; i <= arrayAlphabetizer.length; number++) {

if (number == arrayAlphabetizer[i]) 
{
    arrayAlphabetizer[i] = 0;
    System.out.println(Arrays.toString(arrayAlphabetizer));
} else {
    System.out.print(i);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM