Java Homework trouble asterisks - java

I am having trouble coding. Im trying to make a program that will ask a user to input height and width for a shape. Considering I am taking a java class, I am a newbie. There needs to be two parallel shape of asterisks, can be a square or rectangle.
Thanks!
The code I have so far is kinda frankensteined in
import java.util.Scanner;
public class rectangle {
public static void main(String... args) {
int recHeight = 0;
int recWidth = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter height [-1 to quit] >> ");
recHeight = input.nextInt();
if (recHeight == -1) {
System.exit(0);
}
/* check if number is valid */
if (recHeight < 2 || recHeight > 24) {
System.err.println("--Error: please enter a valid number");
continue; // prompt again
System.out.print("Enter width [-1 to quit] >> ");
recWidth = input.nextInt();
if (recWidth == -1) {
System.exit(0);
}
/* check if number is valid */
if (recWidth < 2 || recWidth > 24) {
System.err.println("--Error: please enter a valid number");
continue; // prompt again
}
for (int col = 0; col < recHeight; col++) {
for (int row = 0; row < recWidth; row++) {
/* First or last row ? */
if (row == 0 || row == recWidth - 1) {
System.out.print("*");
if (row == recWidth - 1) {
System.out.println(); // border reached start a new line
}
} else { /* Last or first column ? */
if (col == recHeight - 1 || col == 0) {
System.out.print("*");
if (row == recWidth - 1) {
System.out.println();
}
} else {
System.out.print(" ");
if (row == recWidth - 1) {
System.out.println();
}
}
}
}
}
}
} while (true);
}
}

I have no idea what they are teaching you with the if and continue's. I think you created an endless loop with do while(true) because you never set it to false.
Here is how we were taught last week, or at least modified to what you need.
import java.io.*;
import java.util.Scanner;
public class SquareDisplay
{
public static void main(String[] args) throws IOException
{
// scanner creation
Scanner stdin = new Scanner(System.in);
// get width
System.out.print("Enter an integer in the range of 1-24: ");
int side = stdin.nextInt();
// check for < 1 or greather then 24
while( (side < 1) || (side > 24))
{
System.out.print("Enter an integer in the range of 1-24: ");
// reget the side
side = stdin.nextInt();
}
// get height
System.out.print("Enter an integer in the range of 1-24: ");
int height = stdin.nextInt();
// check for < 1 or greather then 24
while( (height < 1) || (height > 24))
{
System.out.print("Enter an integer in the range of 1-24: ");
// reget the height
height = stdin.nextInt();
}
// create rows
for( int rows = 0; rows < side; rows++)
{
// creat cols
for( int cols = 0; cols < height; cols++)
{
System.out.print("X");
}
System.out.println();
}
}
}

The following does what you want, and also covers the case they input an invalid number such as example
import java.util.InputMismatchException;
import java.util.Scanner;
public class SquareDisplay {
public static void main(final String... args) {
try (Scanner input = new Scanner(System.in)) {
final int columns = getInRange(input, 1, 24);
final int rows = getInRange(input, 1, 24);
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
System.out.print("X");
}
System.out.println();
}
}
}
private static int getInRange(final Scanner input, final int min, final int max) {
int returnValue = Integer.MIN_VALUE;
do {
System.out.printf("Please enter a value between %d and %d: ", min, max);
try {
returnValue = input.nextInt();
} catch (final InputMismatchException ignored) {
// Ignore, keep asking
}
input.nextLine();
} while (returnValue < min || returnValue > max);
return returnValue;
}
}
Optimisations
Using try-with-resources to handle resource management
Extracting reading the number to reduce duplication
Handling the InputMismatchException to stop it killing the program

Related

Cant figure out how get the last line of the rectangle to work

I have an exercise within my course that asks us to build a program that makes a rectangle made of "*" with the middle being empty. I know I am close as my code almost prints it but it does not produce a full rectangle
any ideas?
/**
* Week 4, Exercise 7.
* #author INSERT YOUR NAME HERE
*/
import java.util.Scanner;
public class Exercise7 {
static Scanner Scan = new Scanner(System.in);
public static void main(String[] args) {
int height ;
int length;
System.out.println("what is the height of the rectangle");
height = Scan.nextInt();
System.out.println("what is the legnth of the rectangle");
length = Scan.nextInt();
for (int row = 1; row <= height; row ++) {
for (int col=1; col<= length; col ++) {
if (col==1 || row == 1 || col == height || row == length) {
System.out.print("* ");
}
else {
System.out.print(" ");
};
};
System.out.println();
};
}
}

2D arrays that change with user input

I've been asked to make a program that prints a 5x5 grid that allows users to input an integer to determine where an "x" will be put. e.g if the user inputs 1 it would print out.
x 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Here's my code. I've built the array but I just can't seem to get it to print out the array where the inputted integer has an effect. Also would I just loop the same code again and again until someone wins or all spaces have been filled.
import java.util.Scanner;
public class Grade {
static Scanner input = new Scanner(System. in );
public static void main(String[] args) {
final int rows = 5;
final int columns = 5;
int one;
int two;
int[][] grid = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("");
}
System.out.println("player one choose your position");
one = input.nextInt();
while (one > 25 || one < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}
System.out.println("player two choose your position");
two = input.nextInt();
while (two > 25 || two < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("" + one);
}
}
}
The code you need to do what you are asking is posted below. Since x is an int in your code you needed an algorithm to make it so that you could set the location properly in the int[][].
import java.util.Scanner;
public class GradeSO
{
Scanner input = new Scanner(System. in);
int remainder;
int down;
int column;
int row;
int rows = 5;
int columns = 5;
int one;
int two;
int[][] grid;
public void makeLocation(int x, int r, int c)
{
remainder = x % c;
down = (int) x / r;
if(x % c!=0)
{
column = remainder-1;
}
else
{
column = remainder;
}
if(x % c==0)
{
row=down-1;
column = remainder+4;
}
else
{
row=down;
}
}
public void makeArray()
{
grid = new int[rows][columns];
System.out.println("Player 1: Please chose a number between 1 and 25");
one = input.nextInt();
while (one > 25 || one < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 1: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}
makeLocation(one,columns,rows);
grid[row][column]= 1;
System.out.println("Player 2: Please chose a number between 1 and 25");
two = input.nextInt();
while (two > 25 || two < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 2: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}
makeLocation(two,columns,rows);
grid[row][column]= 2;
}
public void displayArray()
{
for (int[] smallGrid: grid)
{
for (int elem: smallGrid)
{
System.out.print(elem);
}
System.out.println();
}
}
public static void main(String[] args)
{
GradeSO gSO = new GradeSO();
gSO.makeArray();
gSO.displayArray();
}
}

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

Changing elements in a two dimensional array

What I'm trying to do is generate a 15x15 square of "-" and accept a user input coordinate which will then replace the "-" with a "x" currently my program is just printing a vertical line of "-"
import java.util.*;
public class GameOfLife
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
}
else
System.out.printf("-", boardList[i][j]);
System.out.println();
}
}
}
}
}
}
here you have , this works ... u need to put System.out.println(); outside inner loop as well as put
if(xCoordinate == i){
if(yCoordinate == j){
to one condition ...
public static void main(String[] args) {
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = true;
do {
System.out
.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1) {
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (xCoordinate == i && yCoordinate == j) {
System.out.printf("x", boardList[i][j]);
} else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
}
} while (done);
}
//EDIT note that i changed done to true just to demonstrate that it works ...
try this
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i && yCoordinate==j)
System.out.printf("x", boardList[i][j]);
else
System.out.printf("-", boardList[i][j]);
}
System.out.println();
}
You need to print the new line after you finish printing a whole row first
If I understand well, You want a two dimensional array initialized with '-', to do so you could do
int[][] boardList = new int[15][15];
for (int row = 0; row < 15; row ++)
for (int col = 0; col < 15; col++)
boardList[row][col] = '-';
And then, once you store the user data in xCoordinate and Ycoordinate, you simple do:
boardList[xCoordinate][Ycoordinate] = 'x';
You can try this code:
import java.util.Scanner;
public class StackOverflow
{
public static void main(String[] args)
{
int[][] boardList = new int[15][15];
Scanner myScanner = new Scanner(System.in);
boolean done = false;
System.out.println("1 - Add a being \n 2 - Show current board \n 3 - Show next generation \n 4 - Clear board \n 5 - Add preload pattern \n 6 - Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter the x coordinate: ");
String answer = myScanner.nextLine();
int xCoordinate = Integer.parseInt(answer);
System.out.print("Enter the y coordinate: ");
String answer2 = myScanner.nextLine();
int yCoordinate = Integer.parseInt(answer2);
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
{
if(xCoordinate == i)
{
if(yCoordinate == j)
{
System.out.printf("x", boardList[i][j]);
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
else
{
System.out.printf("-", boardList[i][j]);
}
}
System.out.println();
}
}
}
}

Java - Printing an empty square using nested loops

I am working on printing a quasi-empty square that looks like the example below (10 asterisks across and 10 down for the 2 columns):
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
My code cannot dynamically generate squares as specified by the user's input for the number of rows and columns (it is working for 10 rows and 10 columns, but as soon as I change the number to 20, the number of the asterisks does not change. The following is my code:
String STAR = "*";
String star1 = "**********";
int MAX = 10;
for (int row = 0; row <= MAX; row += 1 ) {
for (int col = 0; col <= MAX ; col += 10) {
if (row == 0 && col == 0)
System.out.println(star1);
if (row >= 1 && row <= 4)
System.out.println(STAR + " " + STAR);
if (row == 10 && col == 10)
System.out.println(star1);
}
}
Any help/advice is welcomed regarding the dynamism of the code.
String star = "*";
String space = " ";
int MAX = xxx;
for (int row = 0; row < MAX; row++) {
for (int col = 0; col < MAX; col++) {
if (row == 0 || row == MAX - 1) {
System.out.println(star);
} else if (col == 0 || col == MAX - 1) {
System.out.println(star);
} else {
System.out.println(space);
}
}
}
Look at your nested loop:
for (int col = 0; col <= MAX ; col += 10) {
So when col is 10, you're really only just iterating once... you might as well not have the nested loop at all.
Additionally, both star1 and the string literal with spaces have a fixed number of characters in them, clearly related to the number of columns.
I'm assuming this is homework, so I won't give any more hints than that to start with, but hopefully that'll get you thinking along the right lines...
You should change the 3 occurrences of 10 in your two for loops by the MAX variable, so when the user define another size, your for loop will take his input instead of the 10 value.
Also take a look at your last if statement there where it says if (row == 10 && col == 10) and think about it for a second. Once you have hit 10 rows and 10 columns, you are just going to print your final horizontal line of star1 regardless of what MAX is set too.
Like mentioned above, the nested for loop is unnecessary and can be inefficient if you plan to create larger rectangles in the future (not saying you're going to have to but try to stay away from nested for loops if you can). Instead, just print star1 before your loop begins and after it exits. The body of the loop should be simple enough. Hope this helps.
class Square
{
public static void main(String[] args)
{
String tenStars="**********";
String oneStar="*";
int count=0;
System.out.println(tenStars);
count++;
while(count<=8)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(tenStars);
}
}
this should work
public static void hallowSquare(int side)
{
int rowPos, size = side;
while (side > 0)
{
rowPos = size;
while (rowPos > 0)
{
if (size == side || side == 1 || rowPos == 1 || rowPos == size)
System.out.print("*");
else
System.out.print(" ");
rowPos--;
}
System.out.println();
side--;
}
}
you can use something like this with one user input ... this is working
public static void drawSquare(int size)
{
for(int i=1; i<size ;i++)
System.out.print("*");
System.out.println("");
for(int i=0; i<50 ;i++)
{
System.out.print("*");
for(int j =0; j<size-3; j++)
System.out.print(" ");
System.out.println("*");
}
for(int i=1; i<size ;i++)
System.out.print("*");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
drawSquare(50);
}
you should just create a class in put this inside your class and run it ... I hope this will help you ....
class Star8
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(i==2||i==3||i==4 )
{
System.out.print("* *");
break;
}
else
{
System.out.print("*");
}
}
System.out.println();
}
}
}
Hope this helps, simplify your thinking mate. Think about the axis x and y and work by that logic. Make a nested loop on ur for loop that passes lines, in each case loop the number of
the size of square and print a space, after the nested loop print the "*".
> for (int b=0;b<ans*2-3;b++)
This nested loop has the max value of b because:
remember that while ur printing, each "*" is distanced from the other by a space, and remember u are only counting space between the first and last column. Meaning all space
between x=0 and x=squaresize, therefore max b should be the space between these 2 coords.
which are: squaresize * 2 /the 2 is for the added spaces/ -3/* -3 because u leave out the first coord(x=0),last coord(x=squaresize), AND 1 space added from the former loop.
import java.util.Scanner;
public class AsteriksSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input= new Scanner(System.in);
int ans;
System.out.print("Enter the size of the side of the square: ");
ans=input.nextInt();
String ast="*";
if (ans>0 && ans<21){
for(int i=0;i<=ans-1;i++){
System.out.print("* ");
}
System.out.println("");
for(int i=1;i<=ans-2;i++){
System.out.print("*");
for (int b=0;b<ans*2-3;b++){
System.out.print(" ");
}
System.out.println("*");
}
for(int i=1;i<=ans;i++){
System.out.print("* ");
}
}
}
}
class square1
{
public static void main(String[] args)
{
String star = "*";
String space = " ";
int MAX = 5;
for (int row = 0; row < MAX; row++)
{
for (int col = 0; col < MAX; col++)
{
if (row == 0 || row == MAX - 1)
{
System.out.print(star);
} else if (col == 0 || col == MAX - 1)
{
System.out.print(star);
} else {
System.out.print(space);
}
}
System.out.println();
}
}
}
This code should do the trick.
package javaPackage;
public class Square {
public static void main(String [] args)
{
for (int i=0;i<=10;i++)
{
for (int j=0;j<=10;j++)
{
if(i==0||i==10){
System.out.print("x");
}
else if(j==0||j==10){
System.out.print("x");
}
else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
If the interpreter sees that you're on the first and last line(i=0 and i=10), it will fill the row with x. Else, it will only print a x at the beginning and the end of the row.
you can use below two methods.
1) One with minimal line of code.
for (int i = 0; i <= 9; i++) {
if (i == 0 || i == 9) {
System.out.println("* * * *");
} else {
System.out.println("* *");
}
}
OR
2) With the help of two for loops
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
if (i == 0 || i == 9) {
System.out.print("*");
} else {
if (j == 0 || j == 9) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
Thanks,
Stuti
Here's another solution, a more versatile one. It lets you create a hollow rectangle of height "h" and width "w"
private static void hallowSquare(int h, int w)
{
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
if (j==1|| j==w || i==1 || i==h )
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
}
}
import java.util.Scanner;
class Star
{
public static void main(String...args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row : ");
int row=sc.nextInt();
System.out.print("Enter the column : ");
int column=sc.nextInt();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
for(int i=row-2;i>=1;i--)
{
System.out.println();
System.out.print("*");
for(int k=1;k<=column-2;k++)
{
if(i<1)
{
break;
}
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
}
}
I am hopeful the code below can help, used very simple coding and have the required result.
a=eval(input('Provide the height of the box: '))
b=eval(input('Provide the width of the box: '))
d=a-2
r=b-2
if a >= 1:
print('*'*b)
if a > 1:
for i in range(d):
print('*',end='')
for i in range(r):
print(' ',end='')
print('*')
print('*'*b,end='')
The result is:

Categories