so I have a 2D arry with defaul value 0, and what I want to do is to accept a value from a user to change
0s to 1s depending on the accepted value.

for example:

we have an arry like this

0000
0000
0000
0000

and the user enters 3
the arry shoule be

1110
0000
0000
0000

doesn't matter the order of 1s , they can be anywhere in the arry

how do I do that?
waht type of loops and conditions I need ?

missed something:
if the value is 1 it can't be overwritten
for exmaple
111
000
000
000

I can't overwrite in index[0][0] because it is already 1.

You would need to use nested loops. Inside the inner loop, index elements in the array. If they are 0, change to 1. If 1 skip it. Count the numer of changes made and exit when done.

but it will change all the 0s to 1s
if the user enters 2 I want to change only 2 0s to 1s.

Not if you are counting like i suggested:

Count the numer of changes made and exit when done.

In your inner loop you should check whether the number of 1's you have is equal to the entered value. If not, continue changing 0's to 1's, if equal already, don't change the remaining 0's anymore.

Edited 4 Years Ago by dimasalang

Comments
please show me in code

The nested loop is used as others said (to traveral through a 2D array). Outside of the loop should be a variable holding the total number you are going to change inside the array (and should be greater than 0). Also (one way to exit a nested loop), have a boolean variable with value false (i.e. isBreak=false;). Inside the inner most loop, check whether the value inside the current array index is equal to 1. If so, use continue; to let it keep going. Right below the continue statement, change the value of the array to 1, and decrease the value of the total number by 1. Then (!important!) check if the total number is equal to 0. If it is, change the boolean variable to true and call break; to immediately exit the inner most loop. At the end of the outter loop, check if the isBreak is true. If it is true, call break; again to immediately get out of the outter loop.

Edited 4 Years Ago by Taywin

try something like this

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

        for (int j=0; j<numb[i].length; j++) {
             if(y != x){
                numb[i][j] = 1;
                y = y +1;
             }
            System.out.print(" " + numb[i][j]);
        }
    System.out.println("");
}

//x - is the input from your user
//y - is the tester if the number of 1's is equal to the number your user have inputted.

Edited 4 Years Ago by dimasalang

This question has already been answered. Start a new discussion instead.