# How can I fill a matrix with only one number in it?

I have a question how can I do the following:

the votes of 5 people are going to be registered for the election of the mayor of the city of Merida in which 4 candidates will participate. each person can vote for only one candidate who is registered with a one and for the candidates who did not vote with a zero.

my doubt is how to make each row only have a 1 and the rest of the positions of the row have a 0, any suggestion ?

`````` public void votar() {

for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {

votos = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero de su candidato: "));
/*
- si presiono un 1 vota por el candidato 1(y el resto de candidatos dé la fila 1
debería ser  0)

- si presiono 2 vota por el candidato 2(el resto de candidatos  0) de la fila 2 y
así  sucesivamente  */

//LOGIICA....

}

}
}``````

1voto

gbianchi Points 11849
``````public void votar() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
votos = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero de su candidato: "));
}
}
}``````

We go from 0 to 3 something (you don't specify what it is I guess it will be an array) We traverse from 0 to 3 something else (will it be a matrix?)

for each row and column => we get a number of the user...

and there is no more code...

The first question is... why do we go through the matrix?

Imagining your logic, if each row is a voter, and each column is who we voted for, we don't need to go through the columns... only the rows...

``````public void votar() {
for (int i = 0; i < 3; i++) {
votos = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero de su candidato: "));
}
}``````

Now... to designate a 1 somewhere... and 0 everywhere else, assuming that the number you entered is the person you voted for, then let's put a 1 in that position... and 0 everywhere else... and now yes, let's go down the column ;)

``````public void votar() {
for (int i = 0; i < 3; i++) {
votos = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero de su candidato: "));
for (int j = 0; j < 3; j++) {
if (votos = j) //chequealo, no es exactamente asi
{
//aca va un 1 en la posicion de la matriz
}
else
{
//aca va un cero, porque por este no voto...
}
}
}
}``````

0voto

Neyer Points 690

You could do it like this

``````public void votar() {

for (int i = 0; i < 5; i++) {
num_candidato = Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero de su candidato: "));
for (int j = 0; j < 4; j++) {
if(num_candidato = j){
//poner uno en la posicion[i][j]
}else{
//poner cero en la posicion[i][j]
}
}

}
}`````` 