简体   繁体   English

如何使用单独的方法替换数组的值?

[英]How to replace the value of array using separate method?

Here in array I insert 0 value in all array index, now I want to check if any array index is equal to 0, then replace the value 0 by value 1, but only one time. 在数组中,我在所有数组索引中插入0值,现在我要检查是否有任何数组索引等于0,然后将值0替换为值1,但仅替换一次。 for example at the beginning it will find index [0]==0 then replace it by 1 then stop the execution. 例如,在开始时它将找到index [0]==0然后将其替换为1,然后停止执行。 if index[0]==1 , then loop need to find next index where value==0 and replace that value 0 with 1. 如果index[0]==1 ,则循环需要找到下一个索引,其中value==0并将该值0替换为1。

public class test {
    static int roomArray[] = new int[10];
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            roomArray[i] = 0;
            System.out.println(roomArray[i]);
        }
        test.book();
    }
    public static void book() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the room you want to book");
        int desiredRoom = sc.nextInt();
        for (int i = 0; i < 10; i++) {
            if (roomArray[i] == 0) {
                roomArray[desiredRoom] = 2;
            }
        }
    }
}

You can change it to 您可以将其更改为

 int desiredRoom= sc.nextInt();
 if(roomArray[desiredRoom]==0){
       roomArray[desiredRoom]= 2;
 }

so you are checking and setting the same position 所以您要检查并设置相同的位置

Your code and your requirements to not really match. 您的代码和要求不完全匹配。 If you go for 如果你去

now i want to check if any array index ==0; 现在我想检查是否有任何数组索引== 0; then replace the value 0 by value 1, but only one time. 然后将值0替换为值1,但只能替换一次。 for example in the begining it will find index [0]==0 then replace it by 1 then stop the execution. 例如,在开始时它将找到索引[0] == 0,然后将其替换为1,然后停止执行。 if index[0]==1, then loop need to find next index where value ==0 and replace that value 0 with 1. 如果index [0] == 1,则循环需要查找下一个索引,其中value == 0并将该值0替换为1。

then it could be like adding a break or even return 那么可能就像添加一个休息甚至返回

for (int i=0; i<10; i++){
  if(roomArray[i]==0){
    roomArray[desiredRoom]= 2;
    break;
  }
}

If you want to check only the desired rom, then it is like Scary Wombats answer. 如果您只想检查所需的rom,就好比Scary Wombats的答案。

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

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