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.
NormR1
Posting Sage
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16
Not if you are counting like i suggested:
Count the numer of changes made and exit when done.
NormR1
Posting Sage
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16
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.
dimasalang
Junior Poster in Training
76 posts since Nov 2010
Reputation Points: 11
Solved Threads: 12
Skill Endorsements: 2
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.
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
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.
dimasalang
Junior Poster in Training
76 posts since Nov 2010
Reputation Points: 11
Solved Threads: 12
Skill Endorsements: 2
Question Answered as of 7 Months Ago by
NormR1,
dimasalang
and
Taywin