I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing
public class TestProgram {
public static void main(String[] args) {
TestProgram test = new TestProgram();
test.draw(15, 4);
}
public void draw(int x, int y) {
// System.out.println(".");
System.out.println();
int i = 0;
int j = 0;
for (i = 0; i < x; i++) {
System.out.print(".");
// continue;
}
for (j = x; j > y; j--) {
System.out.println(".");
System.out.print("\t\t");
System.out.println(".");
}
for (int k = 0; k <= x; k++) {
System.out.print(".");
}
}
}
How about:
public class TestProgram {
public static void main(String[] args) {
TestProgram test = new TestProgram();
test.draw(15, 4);
}
public void draw(int x, int y) {
System.out.println(generateLine(x, '.'));
for (int i = 1; i< y-1; i++) {
System.out.println("." + generateLine(x-2, ' ') + ".");
}
System.out.println(generateLine(x, '.'));
}
private String generateLine(int x, char character) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < x; i++) {
stringBuilder.append(character);
}
return stringBuilder.toString();
}
}
I am not sure i understood currectly but you're trying to print squares without swing? But you're using system.out.print. Its a bit confusing but if its for learning programming homework from school here you go to make a square with for loops:
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
for (int i = 0; i < height - 2; i++) {
System.out.print("*");
for (int j = 0; j < width - 2; j++) {
System.out.print(" ");
}
System.out.println("*");
}
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
}
But if you want to make rectangles (Because you mentioned swing) you should check java.awt.Rectangle2D and Rectangle:
https://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
You can do it in this way:
void rectangleDraw(int x, int y) {
String line1 = new String(new byte[x]).replaceAll("", ".");
String line2 = "." + new String(new byte[x - 2]).replaceAll("", " ") + ".";
System.out.println(line1);
for (int i = x; i > y; i--) {
System.out.println(line2);
}
System.out.println(line1);
}
Related
How could I optimise this code to take the String[] games values from the main method and have a separate method: public static int points(String[] games). I am super new to Java and don't really understand how to invoke methods.
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (int i = 0; i < games.length; i++) {
String[] pieces = games[i].split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
} else if (x == y) {
sum = sum + 1;
}
}
System.out.println(sum);
}
}
You can write something like
public class TotalPoints {
public static void main(String[] args) {
int sum = points(args);
System.out.println(sum);
}
public static int points(String[] games) {
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (int i = 0; i < games.length; i++) {
String[] pieces = games[i].split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
} else if (x == y) {
sum = sum + 1;
}
}
return sum;
}
}
And when you run this class, pass the arguments from command line like
java TotalPoints "1:0" "2:0" "3:0" "4:0" "2:1" "3:1" "4:1" "3:2" "4:2" "4:3"
very simple:
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int result = points(games);
}
public static int points(String[] games) {
//dowhat ever you want and return an int value
}
}
I suggest this to you
public class TotalPoints {
public static void main(String[] args) {
String[] games = {"1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"};
int sum = points(games);
System.out.println(sum);
}
private static int points(String[] games) {
int sum = 0;
int matches = 10;
int x = 0;
int y = 0;
for (String game : games) {
String[] pieces = game.split(":");
x = Integer.parseInt(pieces[0]);
y = Integer.parseInt(pieces[1]);
}
for (int j = 0; j < matches; j++) {
if (x > y) {
sum = sum + 3;
}
else if (x == y) {
sum = sum + 1;
}
}
return sum;
}
}
I replace for (int i = 0; i < games.length; i++)
by
for (String game : games)
it's a simpler way to browse a list
I am trying to build a simple pacman game, and I just got started.
Currently my constructor looks like this:
static String[][] board;
static int pacmanBornHeight;
static int pacmanBornWidth;
public PacmanKata(int height, int width) {
board = new String[height][width];
pacmanBornHeight = (int) Math.floor(height / 2);
pacmanBornWidth = (int) Math.floor(width / 2);
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
board[i][j] = "*";
}
}
board[pacmanBornHeight][pacmanBornWidth] = "V";
}
This constructor set up the board and the pacman will be located at the middle, I used "V" as the symbol.
I try to create two methods currenlty, move up and down.
Here is the setup:
I first called the tickUp method:
public void tickUp(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
board[pacmanBornHeight - counter][pacmanBornWidth] = "V";
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight - innerTimer][pacmanBornWidth] = " ";
}
counter++;
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
} //end going UP
And I print out this to console(I initialized a 10 by 10 board):
Pacman moved up three steps, as expected, and eat three dots. I slightly modified and created a move down method:
public void tickDown(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
board[pacmanBornHeight + counter][pacmanBornWidth] = "V";
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight + innerTimer][pacmanBornWidth] = " ";
}
counter++;
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
}//end tickDown
Now I called tickDown and asked it to move down 3 steps, but I got this result:
The trouble I am having is, I do not know how to locate the Pacman last location. The move down method simply created a new Pacman and moved down 3 steps, that is not what I want. How can I fix this?
Change your tickUp and tickDown methods to save the new position of your Pacman:
public void tickDown(int steps) {
int counter = 1;
int timer = 0;
for (int loop = 0; loop < steps; loop++) {
for (int innerTimer = 0; innerTimer < counter; innerTimer++) {
board[pacmanBornHeight + innerTimer][pacmanBornWidth] = " ";
}
pacmanBornHeight += counter;
//Allow for wraparounds:
if (pacmanBornHeight > board.length) {
pacmanBornHeight = 0;
}
board[pacmanBornHeight][pacmanBornWidth] = "V";
timer++;
}
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
System.out.println("-------------------------");
}//end tickDown
I moved the loop to write spaces in the board to the beginning of the outer loop; that way you get the spaces based on the starting position of Pacman. Once you've written the spaces to the array, you update Pacman's position and write it in the array.
Edit:
Here's an example showing how you'd use a one-dimensional array as your board:
public class PacmanKata {
static String[] board;
static int pacmanPosition;
static int boardHeight;
static int boardWidth;
public static void main(String[] args) {
PacmanKata kata = new PacmanKata(10,10);
kata.tickUp(7);
kata.tickRight(9);
}
public PacmanKata(int height, int width) {
boardHeight = height;
boardWidth = width;
board = new String[height*width];
int offset = (width + 1) % 2;
pacmanPosition = (int) Math.floor((height + offset)*width/2);
for (int i = 0; i < board.length; i++) {
board[i] = "*";
}
board[pacmanPosition] = "V";
}
private void printBoard() {
for (int i = 0; i < board.length; i++) {
System.out.print(board[i]);
if ((i+1) % boardWidth == 0) {
System.out.println();
}
}
System.out.println("-------------------------");
}
public void tickUp(int steps) {
int counter = -1 * boardHeight;
for (int loop = 0; loop < steps; loop++) {
//Current position = ' '
board[pacmanPosition] = " ";
//Pacman's position changes:
pacmanPosition += counter;
//Allow for wraparounds:
if (pacmanPosition < 0) {
pacmanPosition += board.length;
}
//Update the board with Pacman's new position:
board[pacmanPosition] = "V";
}
printBoard();
}//end tickUp
public void tickRight(int steps) {
int counter = 1;
for (int loop = 0; loop < steps; loop++) {
//Current position = ' '
board[pacmanPosition] = " ";
//Pacman's position changes:
pacmanPosition += counter;
if (pacmanPosition % boardWidth == 0) {
pacmanPosition -= boardWidth;
}
//Update the board with Pacman's new position:
board[pacmanPosition] = "V";
}
printBoard();
}//end tickUp
}
Instead of having pacmanBornWidth and pacmanBornHeight fields, you should have a field with pacman current position (all fields shouldn't be static):
String[][] board;
java.awt.Point pacmenPos;
public PacmanKata(int height, int width) {
board = new String[height][width];
pacmanPos = new Point((int) width/2, (int) height/2);
for (int i = 0; i < boardHeight; i++) {
for (int j = 0; j < boardWidth; j++) {
board[i][j] = "*";
}
}
board[pacmanPos.x][pacmanPos.y] = "V";
}
Now replace all occurrences of pacmanBornWidth and pacmanBornHeight with pacmanPos.x and pacmanPos.y.
And in your tickUp and tickDown methods, just update pacman position:
public void tickUp(int steps) {
...
pacmanPos.translate(0, steps);
...
}
public void tickDown(int steps) {
...
pacmanPos.translate(0, -steps);
...
}
This will also work the same if you add tickLeft and tickRight methods:
public void tickLeft(int steps) {
...
pacmanPos.translate(-steps, 0);
...
}
public void tickRight(int steps) {
...
pacmanPos.translate(steps, 0);
...
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
The output of the code displays the following:
The code below seems pretty funky to me, even as a newbie. I imagine the code can be done more efficiently or at least lines of code can be saved without having to whip out so many loops.
If anyone can provide a cleaner solution, thanks in advance.
public class diamond {
public static void main(String[] args) {
for (int c=1; c<=10; c++) {
for (int d=1; d<=11-c; d++) {
System.out.print("*");
}
for (int e=2; e<c*2; e++) {
System.out.print(" ");
}
for (int i=1; i<=11-c; i++) {
System.out.print("*");
}
System.out.println();
}
for (int f=2; f<=10; f++) {
for (int g=1; g<=f; g++) {
System.out.print("*");
}
for (int h=2; h<22-f*2; h++) {
System.out.print(" ");
}
for (int j=1; j<=f; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
The key is to notice repetitive patterns in your code and factor it out.
You could use a helper method to print a series of N characters:
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
You can generalize the approach by using constants for the characters involved and the size of the diamond.
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
And add another helper method to print a row with N instances of one character on the outside, and 2 * (Size - N) characters on the inside:
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
Your code then becomes:
public class diamond
{
private static final char OuterChar = '*';
private static final char InnerChar = ' ';
private static final int Size = 10;
public static void printNTimes(char value, int n) {
for (int i = 0; i < n; i++) {
System.out.print(value);
}
}
private static void printRow(int n) {
printNTimes(OuterChar, n);
printNTimes(InnerChar, (Size - n) * 2);
printNTimes(OuterChar, n);
System.out.println();
}
public static void main(String[] args) {
for (int c = Size; c >= 1; c--) {
printRow(c);
}
for (int c = 2; c <= Size; c++) {
printRow(c);
}
}
}
int max=9,min=10;
for(int i=0;i<19;i++){
for(int j=0;j<20;j++){
if(j<min || j>max){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
if(i<9){
min--;
max++;
}
else {
min++;
max--;
}
System.out.println();
}
I find this rather clear but YMMV.
for( int i = 10; i >= 1; i-- ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
for( int i = 1; i <= 10; i++ ){
String s = "**********".substring(0, i);
System.out.printf( "%-10s%10s\n", s, s );
}
Since this is repeated within the loop:
for (int d=1; d<=11-c; d++)
{
System.out.print("*");
}
you could write it to a variable and print it out twice. That would eliminate two loops. (one subloop in each outer loop)
I like to wrap logic in code that is easy to read and maintain so instead of doing loads of nested for-loops I wrote a class with descriptive methods.
package se.wederbrand.stackoverflow.diamond;
import java.util.ArrayList;
import java.util.List;
public class Diamond {
final List<String> rows;
public static void main(String[] args) {
System.out.println(new Diamond(10));
}
public Diamond(int width) {
this.rows = new ArrayList<>();
for (int stars = 1; stars <= width; stars++) {
// add all rows, start from the middle and build around it
addRows(stars, width);
}
}
private void addRows(int stars, int width) {
String row = generateRow(stars, width);
// add on top
this.rows.add(0, row);
if (stars > 1) {
// add to bottom
this.rows.add(row);
}
}
private String generateRow(int stars, int width) {
String row = "";
int spaces = width - stars;
for (int j = 0; j < stars; j++) {
row += "*";
}
for (int j = 0; j < spaces; j++) {
row += " ";
}
for (int j = 0; j < stars; j++) {
row += "*";
}
return row;
}
#Override
public String toString() {
String diamond = "";
for (String row : rows) {
diamond += row + System.lineSeparator();
}
return diamond;
}
}
This is an fun question as you get to see how everybody takes a different approach to solving it. This way just gives you a string that is "padded" with another character on the other side.
public static void main(String[] args) {
for (int c = 1; c <= 10; c++) {
System.out.println(printPadded(11 - c, '*', (c - 1) * 2, ' '));
}
for (int f = 10; f >= 2; f--) {
System.out.println(printPadded(11 - f, '*', (f - 1) * 2, ' '));
}
}
public static String printPadded(int padCount, char padCharacter,
int middleCount, char middleCharacter) {
StringBuilder s = new StringBuilder(padCount * 2 + middleCount);
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
for (int i = 0; i < middleCount; i++) {
s.append(middleCharacter);
}
for (int i = 0; i < padCount; i++) {
s.append(padCharacter);
}
return s.toString();
}
Very simple but I cannot seem to figure it out, I simply need to translate the while loops into do-while. Objective is to print 1-9 and 9-1 one as such "1,22,333,4444" etc. Thank you if you help me!
int y = 1;
int x = 1;
while (x < 10) {
y = 1;
while (y <= x) {
y++;
System.out.print(x + "");
}
System.out.println();
x++;
}
int a = 9;
int b = 1;
while (a >=1) {
b = 1;
while (b<= a) {
b++;
System.out.print(a + "");
}
System.out.println();
a--;
}
My attempt prints 1-9 but as single numbers and infinitely runs, but does not print anything after 9 the first time.
int c = 1;
int d =1;
do { System.out.print(c +"");
c++;
System.out.println();
}
while (c<10);{
y=1;
while (d<=c);
}
Looks like we are doing your homework...
public class Test {
public static void main(String[] args) {
int c = 1;
do {
int d =1;
do{
System.out.print(c);
d++;
} while (c>=d);
System.out.println("");
c++;
}
while (c<10);
}
}
This is a basic usage:
x=1;
do{
//hello
x++;
} while(x<=10);
Apply it as you need. We can't really do your homework.
What you want is a nested do-while.
int x = 1;
do {
int p = 0;
do {
System.out.print(x);
}
while(p < x)
System.out.println();
x++;
}
while(x < 10)
But I should probably add a for loop would make a lot more sense here:
for(int x = 0; x < 10; x++)
{
for(int p = 0; p < x; p++)
{
System.out.print(x);
}
System.out.println();
}
As you want to run in infinite loop just use:
do {
int c = 1;
do {
System.out.println(c);
c++;
} while (c < 10);
} while (true);
This will run infinitely and print your desired strings:
StringBuilder result1= new StringBuilder();
StringBuilder result2 = new StringBuilder();
do
{
for(int i = 1; i < 10; i++)
{
for(int j = 0; j < i; j++)
{
result1.append(i);
}
result1.append(",");
}
for(int i = 9; i > 0; i--)
{
for(int j = 0; j < i; j++)
{
result2.append(i);
}
result2.append(",");
}
System.out.println(result1);
System.out.println(result2);
}while(true);
I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}