How to make a rectangle of characters?
I need to make such a picture appear in the console
**********
* *
* *
* *
**********
But I get this:
*********
*********
*********
*********
*********
Sides a and b are entered from the console.
int a = requestNumber();
int b = requestNumber();
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
if (j == 0 || j < (b - 1))
System.out.print("*");
else {
System.out.print(" ");
}
}
System.out.println();
}
}
A pretty concise way to do it just a few lines:
int a = requestNumber();
int b = requestNumber();
System.out.println(" " + new String(new char[a]).replace("\0", "*"));
for (int i = 0; i < b; i++) {
System.out.println("*" + new String(new char[a]).replace("\0", " ") + "*");
}
System.out.println(" " + new String(new char[a]).replace("\0", "*"));
EDIT: Fixed typo, works now!
public class Rectangle {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.printRectangle(7,9);
}
private void printRectangle(int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if ((isFirstOrLastRow(i, row) && isFirstOrLastCol(j, col))
|| !(isFirstOrLastRow(i, row) || isFirstOrLastCol(j, col))) {
System.out.print(" ");
}
else {
System.out.print("*");
}
}
System.out.println();
}
}
private boolean isFirstOrLastRow(int currentRow, int row) {
return currentRow == 0 || currentRow == row - 1;
}
private boolean isFirstOrLastCol(int currentCol, int col) {
return currentCol == 0 || currentCol == col - 1;
}
}
The four corners and the middle position should output spaces, so we should judge whether it is the four corners or the middle position,I use isFirstOrLastRow and isFirstOrLastCol to help judge.
here is the result for input 7,9
*******
* *
* *
* *
* *
* *
*******
Related
I am trying to write a program that outputs a Z pattern that is n number of * across the top, bottom, and connecting line using for loops.
Example:
Enter a number: 6
******
*
*
*
*
******
This is my current code, it's producing a half pyramid upside down.
import java.util.*;
public class ZShape {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = n; y >= 1; y--) {
if (y > x) {
System.out.print("* ");
}
else
System.out.print(" ");
}
System.out.println();
}
}
}
This is the logic in the following code:
Loop over each row of the output (so from 0 to n excluded so that we have n rows)
Loop over each column of the output (so from 0 to n excluded so that we have n columns)
We need to print a * only when it is the first row (x == 0) or the last row (x == n - 1) or the column is in the opposite diagonal (column == n - 1 - row)
Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
if (row == 0 || row == n - 1 || column == n - 1 - row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Sample output for n = 6:
******
*
*
*
*
******
(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).
How about using three loops instead?
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println();
for (int x = n-3; x >= 0; x--) {
for (int y = x; y >= 0; y--) {
System.out.print(" ");
}
System.out.println("*");
}
for (int x = 0; x < n; x++) {
System.out.print("*");
}
public class Star {
public static void main(String[] args) {
for (int i = 0; i <=4; i++) {
for (int j = 0; j <=4; j++)
{
if (i==4 || (i+j)==4 || i==0)
{
System.out.print(" * ");
}
else
{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}
Here is a logic to print Z shape:
when i = 1, then the First line will print only "#"
when i = n, then the Last line will print in same way by "#" only
when i = j, that means it will execute one diagonal line by "#" only
Code:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
for (int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--) {
if (i == 1 || i == n || i == j) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
I am new to java and taking an intro course.
I have been able to figure out the majority of my question however i am stuck on the last step.
The end result is supposed to be this using four or less system.out.print or system.out.println statements:
*******
* *****
* ****
* ***
* **
* *
*******
and I have created this
*******
* *****
* ****
* ***
* **
* *
*
This is my code. Is there anything you guys can see that could help?
public class StarPatterns {
public static void main(String[] args) {
int col;
int row;
for (row = 6; row >= 0 ; row--) {
if (row >= 0)
System.out.print("*");
for (col = row; col < 6; col++) {
System.out.print(" ");
}
for (col = row; col > 0; col--) {
System.out.print("*");
}
System.out.println();
}
}
}
public class stars {
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
for (int i=0;i<row;i++)
{
count = i;
System.out.print("*");
for (int c=1;c<col;c++)
{
if (count == 0 || count == row-1)
{
System.out.print("*");
}
else
{
System.out.print(" ");
count--;
}
}
System.out.println("");
}
}
4 System.out prints:
Update:
3 System.out prints:
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
for (int i=0;i<row;i++)
{
count = i;
//System.out.print("*");
for (int c=0;c<col;c++)
{
if (count == 0 || count == row-1 || c == 0)
{
System.out.print("*");
}
else
{
System.out.print(" ");
count--;
}
}
System.out.println("");
}
}
Probably not optimal (memory usage) but maybe good for logic:
Using 2 System.out prints:
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
String strNewLine = "*" + System.lineSeparator();
String str = "*";
String strToPrint;
for (int i=0;i<row;i++)
{
count = i;
for (int c=0;c<col;c++)
{
if (count == 0 || count == row-1 || c == 0)
{
if (c == row-1)
{
strToPrint = strNewLine;
}
else
{
strToPrint = str;
}
System.out.print(strToPrint);
}
else
{
System.out.print(" ");
count--;
}
}
}
}
EDIT: was missing by one : fixed
What do you think of that :
public static void main(String[] args) {
for (int row=0; row<7; row++) {
for (int col=0; col<7; col++) {
System.out.print((col == 0) || (row == 6) || (col > row) ? "*" : " ");
}
System.out.println();
}
}
Result is :
*******
* *****
* ****
* ***
* **
* *
*******
You can do it in 1 without ternary operators since I assume you haven't learned it yet (or at least your instructor wouldn't like you using them):
public class StarPatterns {
public static void main(String[] args) {
int col;
int row;
for (row = 0; row < 7; row++) {
for (col = 0; col < 7; col++) {
String symbol = " ";
if (row == 0 || col == 0 || col > row || row == 6) {
symbol = "*";
}
if (col == 6) {
symbol += System.getProperty("line.separator");
}
System.out.print(symbol);
}
}
}
}
Output:
*******
* *****
* ****
* ***
* **
* *
*******
For my assignment I am supposed to make a Draw a diamond with asterisks using methods.
I figured out how to make the first part (centered triangle)
I cannot for the love of God figure it out. I have spent over 4 hours trying different things and I figured how to make an upside down triangle, but the diamond is not working out.
This is what I have for the first part. Can someone tell me how to flip it so that it will form a diamond when used with an upside down version?
{
int rows = userInputHeight;
int starCount = 1;
int spaceCount = rows - 1;
for( int rowCount = 1; rowCount <= rows; rowCount++ )
{
for( int numb = 1; numb <= spaceCount; numb++ )
{
System.out.print(" ");
}
for( int count = 1; count <=starCount; count++ )
{
System.out.print("*");
}
System.out.println();
starCount += 2;
spaceCount--;
}
}
This is what it displays (UserInputHeight = 10):
*
***
*****
*******
*********
***********
This is what I want (UserInputHeight = 19):
*
***
*****
*******
*********
***********
***********
*********
*******
*****
***
*
This is what I have so far for the second part:
{
int rows = userInputHeight;
int starCount = rows*2;
int spaceCount =userInputPadding;
if (userInputHeight % 2 == 0)
{
userInputHeight+=1;
}
for (int rowCount = rows; rowCount >= 1; rowCount --)
{
for (int i = 0; i <= (rows - rowCount)+ spaceCount; i++)
{
System.out.print(' ');
}
for (int i = 1; i < starCount; i++)
{
System.out.print('*');
}
System.out.println();
starCount -=2;
}
}
Please help.
Try this:
public static void drawDiamond(int height) {
if (height % 2 == 0) throw new AssertionError("Height should be an odd number!");
height = (height + 1) / 2;
drawTop(height);
drawBot(height - 1);
}
public static void drawTop(int height) {
int rows = height;
int starCount = 1;
int spaceCount = rows - 1;
for (int rowCount = 1; rowCount <= rows; rowCount++) {
for (int i = 0; i < spaceCount; i++) {
System.out.print(" ");
}
for (int i = 0; i < starCount; i++) {
System.out.print("*");
}
starCount += 2;
spaceCount--;
System.out.println();
}
}
public static void drawBot(int height) {
int rows = height;
int starCount = 2 * (rows - 1) + 1;
int spaceCount = 1;
for (int rowCount = 1; rowCount <= rows; rowCount++) {
for (int i = 0; i < spaceCount; i++) {
System.out.print(" ");
}
for (int i = 0; i < starCount; i++) {
System.out.print("*");
}
starCount -= 2;
spaceCount++;
System.out.println();
}
}
Here is another angle of looking at it.
Note: height strands from the mid-line to the uppermost point.
public static void DrawDiamond(int height)
{
DiamondTop(height);
DiamondBottom(height);
}
public static void DiamondTop(int height)
{
for (int row = 1; row <= height; row++)
{
for (int padding = height - row; padding > 0; padding--)
{
System.out.print(" ");
}
for (int numberOfAsterisks = (row * 2) - 1; numberOfAsterisks > 0; numberOfAsterisks--)
{
System.out.print("*");
}
System.out.println();
}
}
public static void DiamondBottom(int height)
{
for (int row = height - 1; row > 0; row--)
{
for (int padding = row; padding < height; padding++)
{
System.out.print(" ");
}
for (int numberOfAsterisks = (row * 2) - 1; numberOfAsterisks > 0; numberOfAsterisks--)
{
System.out.print("*");
}
System.out.println();
}
}
Hi there i want to create a triangle using java loops. But what i need is only the borders. I've tried using this syntax but it always shows error. any advice?
int lines = 5;
int c = 2*lines;
for (int i = lines-1; i>=0; i--)
{
for (int j = i; j < lines; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= c; k++)
{
if (k % 2 == 0)
{
System.out.print(" ");
}
else
{
if (k == 0 || k == lines - 1) {
System.out.print("*");
}
}
}
System.out.print("\n");
c -= 2;
}
can you kindly help me . thanks
There's a lot of things wrong with your code...
for (int k = 1; k <= c; k++)
// and then:
if (k == 0 || k == lines - 1) {
k will never be 0
if (k % 2 == 0)
// and then
else
{
if (k == 0 || k == lines - 1) {
a even if k was 0, then 0%2 == 0, so k==0 can never occur
As of right now, your app only prints spaces.
If you want to draw a triangle, the (possibly) simplest way would be to do
public static void main(String[] args) {
int lines = 6;
int cols = lines+1;
for (int line =0; line < lines-1; line++) {
for (int col = 0; col<cols; col++) {
if (col == 0 || col == line) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
for (int col=0; col<cols; col++) {
System.out.print("*");
}
System.out.println();
}
Triangle.java
public class Triangle {
private int lines;
public Triangle(int lines) {
this.lines = lines;
display();
}
public void display() {
int spaces = lines - 1;
int last;
int min = 1;
int max;
for (int i = 0; i < lines; i++) {
last = 2 * i + 1;
max = spaces + last;
for (int j = min; j <= max; j++) {
if (j == spaces + 1 || j == max || i == lines - 1)
System.out.print('*');
else
System.out.print(' ');
}
System.out.println();
spaces--;
}
}
public static void main(String[] args) {
new Triangle(3);
new Triangle(4);
new Triangle(5);
new Triangle(6);
}
}
Output
*
* *
*****
*
* *
* *
*******
*
* *
* *
* *
*********
*
* *
* *
* *
* *
***********
Ex:
*
* *
* *
* *
*********
Code:
int numberOfRows = 5;
for(int i=0; i<numberOfRows; i++)
{
for(int a=0; a<=numberOfRows; a++)
{
int x = numberOfRows - i;
if (a > x) {
if (x==(a-1) || i==(numberOfRows-1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
} else {
System.out.print(" ");
}
}
for(int b=0; b<=i; b++)
{
if(b==i || i==(numberOfRows-1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
I have used two methods and repeated those two methods using for loop.
public class OpenWord {
int i;
String k = " ";
public void space(){
System.out.println("*"+k+"*");
}
public void star(){
System.out.println("*");
}
public void trainagle(){
star();
for ( i=1; i<=10;i++){
space();
k =k+" ";
if(i==10){
k=k.replace(" ", "*");
space();
}
}
}
public static void main(String args[]) {
OpenWord a = new OpenWord();
a.trainagle();
}
}
Output:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
******************
Here's my code: http://pastebin.com/umy0FPvB (LG)
and here's the teacher's code: http://pastebin.com/y5wU0Zpx (LCI)
It's telling me I'm wrong on line 41 of the teacher's code when the LCI is trying to read from the matrix passed from the LG [world()].
I've been sitting on this for a while but I can't seem to figure out what's wrong.
Exception in thread "main" java.lang.NullPointerException
at Console.printWorld(Console.java:41)
at Console.playLife(Console.java:56)
at Console.main(Console.java:30)
--
/**
* The Life game
* #author Noah Kissinger
* #date 2012.2.13
*/
import java.util.Random;
public class Life {
private static boolean[][] matrix;
private static int bL, bH, lL, lH, r, c;
private static long rSeed;
public Life(long seed, int rows, int columns, int birthLow, int birthHigh,
int liveLow, int liveHigh) {
rSeed = seed;
bL = birthLow;
bH = birthHigh;
lL = liveLow;
lH = liveHigh;
r = rows;
c = columns;
createMatrix();
}
public void update() {
updateMatrix();
}
public boolean[][] world() {
return matrix;
}
public static void createMatrix() {
Random seedBool = new Random(rSeed);
boolean[][] matrix = new boolean[r][c];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = false;
}
}
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
matrix[i][j] = seedBool.nextBoolean();
}
}
}
public static void updateMatrix() {
Random seedBool = new Random(rSeed);
boolean[][] matrixCopy = matrix.clone();
for (int i = 0; i < matrix.length; i++)
matrixCopy[i] = matrix[i].clone();
int count = 0;
for (int i = 1; i < matrix.length - 1; i++) {
for (int j = 1; j < matrix[i].length - 1; j++) {
if (matrix[i][j] == false) {
if (matrixCopy[i - 1][j - 1] == true)
count++;
if (matrixCopy[i - 1][j] == true)
count++;
if (matrixCopy[i - 1][j + 1] == true)
count++;
if (matrixCopy[i][j - 1] == true)
count++;
if (matrixCopy[i][j + 1] == true)
count++;
if (matrixCopy[i + 1][j - 1] == true)
count++;
if (matrixCopy[i + 1][j] == true)
count++;
if (matrixCopy[i + 1][j + 1] == true)
count++;
if (count >= bL && count <= bH) {
matrix[i][j] = true;
for (int i1 = 0; i1 < matrix.length; i1++) {
for (int j1 = 0; j1 < matrix[i1].length; j1++) {
matrix[i1][j1] = false;
}
}
for (int i1 = 1; i1 < matrix.length - 1; i1++) {
for (int j1 = 1; j1 < matrix[i1].length - 1; j1++) {
matrix[i1][j1] = seedBool.nextBoolean();
}
}
} else
matrix[i][j] = false;
count = 0;
}
else {
if (matrixCopy[i - 1][j - 1] == true)
count++;
if (matrixCopy[i - 1][j] == true)
count++;
if (matrixCopy[i - 1][j + 1] == true)
count++;
if (matrixCopy[i][j - 1] == true)
count++;
if (matrixCopy[i][j + 1] == true)
count++;
if (matrixCopy[i + 1][j - 1] == true)
count++;
if (matrixCopy[i + 1][j] == true)
count++;
if (matrixCopy[i + 1][j + 1] == true)
count++;
if (count >= lL && count <= lH)
matrix[i][j] = true;
else
matrix[i][j] = false;
count = 0;
}
}
}
}
}
--
/**
* The Console class is a console interface to the Life game.
* #author DH
* #date Sept. 2008
*/
import java.util.Scanner;
public class Console {
/**
* #param args unused
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the size of the matrix(rows, columns) :");
int rows = in.nextInt();
int columns = in.nextInt();
System.out.println("Please enter random seed: ");
long seed = in.nextLong();
System.out.println("Please enter birth range (low, high) :");
int birthLow = in.nextInt();
int birthHigh = in.nextInt();
System.out.println("Please enter live range (low, high): ");
int liveLow = in.nextInt();
int liveHigh = in.nextInt();
try {
Life game = new Life(seed, rows, columns, birthLow, birthHigh, liveLow, liveHigh);
playLife(game);
} catch (IllegalArgumentException e) {
System.out.println("Inappropriate values: " + e.getMessage());
}
}
/**
* Print a boolean matrix
* #param world is a boolean matrix to be printed with # for true and - for false.
*/
public static void printWorld(boolean[][] matrix) {
for (int r=0; r<matrix.length; r++) {
for (int c=0; c<matrix[0].length; c++) {
System.out.print(matrix[r][c] ? " # " : " - ");
}
System.out.println();
}
System.out.println();
}
/**
* Play the game of Life starting with a given state
* #param game is the Life object that provides the current state of Life
*/
public static void playLife(Life game) {
printWorld(game.world());
for (int i=0; i<10; i++) {
game.update();
printWorld(game.world());
}
}
}
Here's your problem. In your createMatrix() method you define a local variable matrix when you really want to modify the field matrix.
You may find it useful to access fields with this, e.g. this.matrix. It makes a clear distinction in the code. However, most IDEs will auto highlight fields and local variables so some people find it unnecessary, it's a question of style and not overly important.
I haven't checked the rest of your program, there may be other errors.
public static void createMatrix() {
Random seedBool = new Random(rSeed);
this.matrix = new boolean[r][c];
for (int i = 0; i < this.matrix.length; i++) {
for (int j = 0; j < this.matrix[i].length; j++) {
this.matrix[i][j] = false;
}
}
for (int i = 1; i < this.matrix.length - 1; i++) {
for (int j = 1; j < this.matrix[i].length - 1; j++) {
this.matrix[i][j] = seedBool.nextBoolean();
}
}
}
boolean[][] matrix = new boolean[r][c];
This line creates a 2-dimensional array of boolean and stores it in a loca variable in the createMatrix method.
So, the static field matrix in the Life class still be null.
This field is read and passed through the world method into the playLife method.
And, next, the call of printLife method trigger NPE.
BTW, why did you implemented the game of life using many static fields and methods?