Reputation: 882
I have a 2 dimensional array that is filled using input from the user. I have most of the code done, but one of the requirements, even though its not what the assignment is actually about, is that if an element is left out of the user's input (they enter input separated by spaces), it is automatically set to 0. How can I set that up?
Upvotes: 0
Views: 57
Reputation: 6515
try this:
public static void main(String [] args) {
int a[][] = new int[3][3];
char ch;
Scanner s = new Scanner(System.in);
System.out.println("Enter 3*3 matrix :");
for (int i = 0; i < 3; i++) {
String value = s.nextLine();
for (int j = 0; j < 3; j++) {
try {
ch = value.replace("\n", "").charAt(j);
if (ch == ' ') {
a[i][j] = 0;
} else {
a[i][j] = Character.getNumericValue(value.replace("\n",
"").charAt(j));
}
} catch (Exception e) {
// a[i][j]=0;
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(" " + a[i][j]);
System.out.println();
}
}
output :
Enter 3*3 matrix :
2
3
4
0 0 2
3 0 0
0 4 0
Upvotes: 0
Reputation: 41
At initialization, all elements in the array are set to a default value of null (Object/String), 0 (int/byte/float/double/short/long) or false (boolean). Provided no values are assigned at initialization, the elements should already hold this value so as long as the user input assigned does not change this it should already be set to 0 depending on primitive/object type.
Upvotes: 1