I need help writing this program in JAVA, this is an introductory java course, s
ID: 3811766 • Letter: I
Question
I need help writing this program in JAVA, this is an introductory java course, so if possible, keep it as basic/simple as possible while still following the instructions. The output should look like the sample execution at the end of the problem.
Write a program which asks the user to enter the size of a grid and display the corresponding grid. The dimensions of the grid will be the same in each dimension, so if the user enters 4, you would display a 4 x 4 grid. If the user enters 10, you would display a 10 x 10 grid, and so on. See below for examples.
Input Validation:
The size of the grid must be a positive integer.
Requirements:
You must design your program to use methods correctly.
You must design your program to theoretically work for any input value.
Hints:
You might want to have a method that takes the grid size and prints one line of the grid that has the plus signs: +--+--+--+--+--+
You might want to have a method that takes the grid size and prints one line of the grid that has the vertical pipes: | | | | | |
You might want to have a method that takes the grid size and using the previous two methods, display the correct result.
Choose your return types wisely.
Sample Execution 1:
Sample Execution 2:
Sample Execution 3:
Explanation / Answer
package grid;
/*
* Hope the program meets your requirements,feel free to comment for doubts
* All The Best :)
* sample input/output
Enter the Grid size:
5
+--+--+--+--+--+
| | | | | |
+--+--+--+--+--+
| | | | | |
+--+--+--+--+--+
| | | | | |
+--+--+--+--+--+
| | | | | |
+--+--+--+--+--+
| | | | | |
+--+--+--+--+--+
*/
import java.util.Scanner;
public class Grid {
// static String horizontal="+--";
// static String vertical="| ";
public static void main(String args[])
{
int gridSize=getGridSize();
int count=0;
while(count<gridSize)
{
for(int i=0;i<gridSize;i++)
{
System.out.print("+--");
}
System.out.println("+");
for(int i=0;i<gridSize;i++)
{
System.out.print("| ");
}
System.out.println("|");
count++;
}
for(int i=0;i<gridSize;i++)
{
System.out.print("+--");
}
System.out.println("+");
}
public static int getGridSize(){
System.out.println("Enter the Grid size:");
Scanner sc = new Scanner(System.in);
int gridSize=sc.nextInt();
if(gridSize<0)
{
System.out.println("The size of the grid must be a positive integer");
gridSize=getGridSize();
//comment the above line and uncomment the below if you want to exit if user entered negative value
// System.exit(1);
}
return gridSize;
}
}