Using For Loop to Print Pattern in Java - java

I need to print this:
I need to print this square using a for loop in java.
This is what I have so far:
public static void main(String [] args)
{
for(int i = 0; i < 5; i++){
System.out.print("O ");
}
System.out.println();
for(int i = 0; i < 4; i++){
System.out.print("O ");
}
}

The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,
int size = 5;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
System.out.print("O ");
}
for (int j = 0; j < i; j++) {
System.out.print(". ");
}
System.out.println();
}
Which outputs (as requested)
O O O O O
O O O O .
O O O . .
O O . . .
O . . . .
Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.
int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("O ");
}
for (int i = 0; i < size; i++) {
System.out.println(sb);
sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}
And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,
int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(arr[j] ? ". " : "O ");
}
System.out.println();
arr[size - i - 1] = true;
}

This is not a 'design pattern' problem. You just need to use the logic with loops.
Here's the logic.
In a square of n x n cells, the ith row contains (n-i) ovals and i
dots, where 0 <= i < n.
Refer to the other answer to see a working snippet.

Related

Why won't my array print the rest of the columns?

I'm very curious about encryption so I went out and gave myself a little task, to encrypt a message (below in my .txt file). I'm not getting the output I want, I'm only getting the first column. Why's it only printing the first column?
Here's my java file:
import java.io.*;
public class EncryptDecrypt {
public static void encrypt() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
String line = in.readLine();
char[][] table = new char[5][5];
// fill array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
// print array
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
System.out.println(table[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
encrypt();
}
}
My .txt file contains:
E5NOWISTHEWINTEROFOURDISCONTENT*
My output is:
E
5
N
O
W
I want my output to be:
E I T W O O D
5 S H I F U I
N E N R S
O T C
W E O
R N
T
E
N
T
This part has an issue
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table.length; j++) {
table[i][j] = line.charAt(j);
}
}
You are only filling characters from j=0 to j=5 as your char array is of size 5 (you are retrieving first 5 characters of the line). I am unsure of what are you trying to achieve as a character array with 5X5 is not the answer.
If your txt file has line delimiters, you can make use of them and read each word into a string and have an array of strings.
I am leaving the explanation here as I couldn't make much out the question
That's because you are just iterating along the rows.
In the for loop, table.length moves along the rows (that is vertically), whereas table[0].length will iterate along the columns, that is on a single row (horizontally)
So you may want to change your loop to:
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
//your code here
}
}
Also, you need to have separate counter for your string. Your value of j is limited to the size of your array column length, namely from 0 to 4.
For idea, try this:
String line = in.readLine();
int cnt = 0;
for(int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
while(cnt<line.length()){
table[i][j] = line.charAt(cnt);
cnt++;
}
}
}

Triangle Word Pattern using Nested Loops in Java

For this assignment, after inputting any word, it will print it in a pattern shown below (in this case, the word is computer):
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Currently, my code is this:
String output = "";
for (int a = word.length()-1; a >= 1; a--)
{
for (int b = 0; b < word.length(); b++)
{
out.print(" ");
}
out.println(word.charAt(word.length()-1-a));
}
for (int c = 0; c < word.length(); c++)
{
out.print(word.charAt(word.length()-1-c));
}
out.print(word.substring(1));
return output + "\n";
The output for my code currently is:
C
O
M
P
U
T
E
RETUPMOCOMPUTER
Any advice or tips is much appreciated, thank you in advance!
The logic is simple, first try to create the last line, using reverse of StringBuilder. Then print each line from the first to the last line.
The last line case is simple.
From the first to the last line - 1, we only need to print those characters that has the distance equal 0, 1, 2 ... to the center of the last line.
public void printTriangle(String input) {
String tmp = input.substring(1);//Take the suffix
StringBuilder builder = new StringBuilder(tmp);
builder = builder.reverse().append(input);//Reverse, then append it
String line = builder.toString();//This is the last line
for(int i = 0; i < input.length(); i++){
for(int j = 0; j < line.length(); j++){
//Print the last line, or those that have distance equals i to the center of the last line
if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
System.out.print(line.charAt(j));
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
Input
COMPUTER
Output
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Input
STACKOVERFLOW
Output
S
T T
A A
C C
K K
O O
V V
E E
R R
F F
L L
O O
WOLFREVOKCATSTACKOVERFLOW
You asked for nested loops, but there are a few other ways including padding it with spaces. If you are allowed to do that, you only need a single loop:
public static void printTriangle(String str){
int len = str.length()-1, idx = 1;
System.out.println(String.format("%"+(len+1)+"s", str.charAt(0)));
for(int x=0; x<str.length()-2; x++){
System.out.print(String.format("%"+(len--)+"s", str.charAt(idx)));
System.out.println(String.format("%"+(idx*2)+"s", str.charAt(idx++)));
}
System.out.println(new StringBuilder(str.substring(1)).reverse().toString() + str);
}
Output:
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Instead of doing a code that will magically work for every case, try using a code that addresses every case:
String someString = "COMPUTER";
switch(someString.length()) {
case 0: System.out.println();
break;
case 1: System.out.println(someString);
break;
default:
int _spaces_before_after = someString.length()-1;
int _spaces_middle = 0;
for(int i=0; i<someString.length(); i++){
if(i!=someString.length()-1){
if(i==0){
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(0));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle = 1;
}
else {
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_middle; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle+=2;
}
_spaces_before_after-=1;
}
else {
for(int j=someString.length()-1; j>=0; j--)
System.out.print(someString.charAt(j));
for(int j=1; j<someString.length(); j++)
System.out.print(someString.charAt(j));
}
}
break;
}
Suppose you have a string str of length n. You'll have a matrix of size n × 2n+1.
First, you need to define the center c of your triangle, which would be the position n
In your first line of the matrix, you draw only the first letter (str[0]) in the center and then go to the next line.
In the second line, you draw the second letter (str[1]) in the positions c-1 and c+1.
In the third line, you draw the third letter (str[2]) in the positions c-2 and c+2.
And so on.
The last line is the trickier. Starting from the center c, you have to draw the whole word str. From the center, you start writing your string forwards and backwards.
I've tried some implementation, it's really simple:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = str.length();
char[][] matrix = new char[n][2*n+1];
char[] chrArr = str.toCharArray();
// initializes the matrix with blank spaces
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
matrix[i][j] = ' ';
}
}
// build the two sides of the triangle
for (int i = 0; i < n - 1; i++) {
matrix[i][n-i] = chrArr[i];
matrix[i][n+i] = chrArr[i];
}
// last line, build the base of the triangle
for (int i = 0; i < n; i++) {
matrix[n-1][n-i] = chrArr[i];
matrix[n-1][n+i] = chrArr[i];
}
// print
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
System.out.print(matrix[i][j]);
}
System.out.print("\n");
}
Here is the sample code running in ideone.
You can try it with any string size.

Asterisk in Nested loops, Java

I am trying to make my code print out the Asterisk in the image, you see below. The Asterisk are align to the right and they have blank spaces under them. I can't figure out, how to make it go to the right. Here is my code:
public class Assn4 {
public static void main(String[] args) {
for (int i = 0; i <= 3; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int x = 0; x <= 1; x++) {
System.out.println(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
}
System.out.println();
}
}
Matrix problems are really helpful to understand loops..
Understanding of your problem:
1) First, printing star at the end- That means your first loop should be in decreasing order
for(int i =7;i>=0; i+=i-2)
2) Printing star in increasing order- That means your second loop should be in increasing order
for(int j =0;j<=7; j++)
Complete code:
for(int i =7;i>=0; i=i-2){ // i=i-2 because *s are getting incremented by 2
for(int j =0;j<=7; j++){
if(j>=i){ // if j >= i then print * else space(" ")
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();// a new line just after printing *s
}
Starting loops with 1 can sometimes help you visualize better.
int stopAt = 7;
for (int i = 1; i <= stopAt ; i += 2) {
for (int j = 1; j <= stopAt; j++) {
System.out.print(j <= stopAt - i ? " " : "*");
}
System.out.println();
}
Notice, how each row prints an odd number of *s ending at the line with 7. So, you start with i at 1 and go through 3 1+2, 5 3+2, and then stopAt 7 5+2.
The nested for loop has to print 7 characters always to make sure *s appear right aligned. So, the loop runs from 1 to 7.
Here the complete code:
for(int i = 0; i < 8; i++){
if( i%2 != 0){
for(int x = 0; x < i; x++){
System.out.print("*");
}
}else{
System.out.println();
}
}

Randomly populating a 2d array

I am using Java and working on 5X5 board game(represented as String[][]) and I looking for an efficient way to randomly place 3 "A"'s, 3 "B",s 3 "C"'s, 3 "D"'s on the board.
I thought about using a nested for loop inside of a while loop to go over each slot, and randomly assign letters to 'slots' on the board, but I want to possibly do it in one pass of the board, if there is a good way to randomly place all 15 letters on the board in one pass.
Any suggestions?
You can use an ArrayList to store the letters (and the empty cells, I'm using a dot . so you can recognize it in the output), then use Collections.shuffle() to put elements of the ArrayList in "random" places. Finally assign each letter to the String[][] array:
public static void main(String[] args)
{
String[][] board = new String[5][5];
List<String> letters = new ArrayList<>();
// fill with letters
for (int i = 0; i < 3; i++) {
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
}
// fill with "empty"
for (int i = 0; i < 10; i++) {
letters.add(".");
}
Collections.shuffle(letters);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = letters.get(i*board.length + j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
Output Sample:
C B . . .
A E . E A
. A . D D
C . . . D
B C E . B
Note:
The operation i*board.length + j will generate consequent numbers 0, 1, 2, 3, ... 24 en the nested loop.
One way: create an ArrayList<Character> or of String, feed it the 15 letters, call java.util.Collections.shuffle(...) on the ArrayList, and then iterate over this List, placing its randomized items into your array.
e.g.,
List<String> stringList = new ArrayList<String>();
for (char c = 'A'; c <= 'E'; c++) {
for (int i = 0; i < 3; i++) {
stringList.add(String.valueOf(c));
}
}
for (int i = 15; i < 25; i++) {
stringList.add(null);
}
Collections.shuffle(stringList);
String[][] gameBoard = new String[5][5];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = stringList.get(i * gameBoard.length + j);
}
}
// now test it
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
System.out.printf("%-6s ", gameBoard[i][j]);
}
System.out.println();
}

Simple Java Pyramid using nested for loops

I am having a great deal of trouble trying to figure out a way to create a pyramid using a user's input. Here is what it is suppose to look like.
Enter a number between 1 and 9: 4
O
O
O
O
OOOO
OOOO
OOOO
OOOO
O
OO
OOO
OOOO
This is what I have so far
public static void main(String[] args) {
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number between 1 and 9: ");
number = keyboard.nextInt();
for (int i = 1; i < 10; i++){
for (int rows = number; number < i; rows++){
System.out.print("O");
}
System.out.println();
}
}
I completely understand of what I am trying to accomplish, but I do not completely understand how for loops work. Any help would be greatly appreciated as I am completely lost!
Basically a for loop works like this
// Take this example (and also try it)
for (int i = 0; i < 10; i++)
{
System.out.println(i);
}
// Explanation
for(int i = 0; // the value to start at - in this example 0
i < 10; // the looping conditions - in this example if i is less than 10 continue
// looping executing the code inclosed in the { }
// Once this condition is false, the loop will exit
i++) // the increment of each loop - in this exampleafter each execution of the
// code in the { } i is increments by one
{
System.out.println(i); // The code to execute
}
Experiment using different starting value, conditions and increments, Try these:
for (int i = 5; i < 10; i++){System.out.println(i);}
for (int i = 5; i > 0; i--){System.out.println(i);}
Replace the for-loops with:
for (int i = 0; i < number ; i++){
System.out.println("O");
}
for (int i = 0; i < number ; i++){
for (int j = 0; j < number ; j++){
System.out.print("O");
}
System.out.println();
}
for (int i = 1; i <= number ; i++){
for (int j = 0; j < i ; j++){
System.out.print("O");
}
System.out.println();
}
OUTPUT (for number = 6):
O
O
O
O
O
O
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
O
OO
OOO
OOOO
OOOOO
OOOOOO
Some for insight..
for(INIT_A_VARIABLE*; CONDITION_TO_ITERATE; AN_OPERATION_AT_THE_END_OF_THE_ITERATION)
You can init more than one variable or call any methods. In java you can init or call the same type of variable/method.
These are valid code statements:
for (int i = 0; i <= 5; i++) // inits i as 0, increases i by 1 and stops if i<=5 is false.
for (int i = 0, j=1, k=2; i <= 5; i++) //inits i as 0, j as 1 and k as 2.
for (main(args),main(args); i <= 5; i++) //Calls main(args) twice before starting the for statement. IT IS NONSENSE, but you can do that kind of calls there.
for (int i = 0; getRandomBoolean(); i++) //You can add methods to determine de condition or the after iteration statement.
Now.. about your homework.. I'd use something like this:
Iterate through the limit of rows and add spaces and the desired character to its position. The position will be determined by the row you are in.
for (int i = 0; i <= 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(' ');
}
for (int j = 0; j < i; j++) {
System.out.print("O ");
}
System.out.println();
}

Categories

Resources