From what I understand your program is working correctly but you want to separate the logic of reading the height from the user from the method tehtava7()
So, basically you need to move that logic to the main method:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write the height: ");
int height = scanner.nextInt();
}
Then you can use that height to pass it as a parameter to tehtava7(...), so your method signature would become:
public static void tehtava7(int height) {
// Your code here
}
But now, you want to return the 2D char array from it, so we need to change void for char[][] and add a return at the end, so in the end tehtava7 would end up as:
public static char[][] tehtava7(int height) {
char[][] array = new char[height][height];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (row == col || col == 0 || col == height - 1) {
array[row][col] = 'X';
} else {
array[row][col] = ' ';
}
}
}
return array;
}
And now you can use it on the main method like this:
tehtava7(height);
But as it returns a char[][] and you still need to print the N pattern you can do it this way:
printTwoDimCharArray(tehtava7(height));
And in the end, your whole program would look like this:
import java.util.Scanner;
public class PatternSample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Write the height: ");
int height = scanner.nextInt();
/*
Or you could make the call to tehtava7 and store it
in a 2D char array, and then use that as a parameter
for the print method like this:
char[][] tehtavaArray = tehtava7(height);
printTwoDimCharArray(tehtavaArray);
*/
printTwoDimCharArray(tehtava7(height));
}
private static char[][] tehtava7(int height) {
char[][] array = new char[height][height];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (row == col || col == 0 || col == height - 1) {
array[row][col] = 'X';
} else {
array[row][col] = ' ';
}
}
}
return array;
}
private static void printTwoDimCharArray(char[][] myarray) {
for (int i = 0; i < myarray.length; i++) {
for (int j = 0; j < myarray[i].length; j++) {
System.out.print(myarray[i][j]);
}
System.out.println();
}
}
}
And the output:
Write the height: 7
X X
XX X
X X X
X X X
X X X
X XX
X X
I must say, congratulations, you were almost there, keep the good work :)