Printing specified alphabet in pyramid format - java

I have some problem when trying to print out alphabet XXYY in half pyramid format using Java. Here is the expected output when user entered height of 7:
XX
YYXX
XXYYXX
YYXXYYXX
XXYYXXYYXX
YYXXYYXXYYXX
XXYYXXYYXXYYXX
And here is my code:
public static void main(String[] args){
int height = 0;
String display = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
height = sc.nextInt();
for(int i = 1; i <= height; i++){
for(int j = 1; j <= i; j++){
if(j %2 == 0){
display = "YY" + display;
}else{
if(j == 1){
display = "XX";
}
}
System.out.print(display);
}
System.out.println();
}
}
What my logic is I thinking to check for even/odd row first then add the XX or YY to the display string. First I check for first row, then I add XX to the display string. Then, if even row, I append YY to the front of the display string.
But my problem is I not sure how to count the amount of XX and YY for each row. Here is my output:
XX
XXYYXX
XXYYXXYYXX
XXYYXXYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXXYYYYYYXX

IMHO, you're over-complicating things. In each row you have the same number of pairs of letters as the row number (one pair on the first row, two on the second, etc). The first row starts with "XX" and then the beginnings alternate between "XX" and "YY". In a similar fashion, within the row, after determining what you started with, you alternate between the two pairs of letters:
for (int row = 0; row < height; ++row) {
for (int col = 0; col <= row; ++col) {
if ((col + row) % 2 == 0) {
System.out.print("XX");
} else {
System.out.print("YY");
}
}
System.out.println();
}

This should do it:
public static void main (String[] args) throws java.lang.Exception
{
int ht = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter height: ");
ht = sc.nextInt();
String text = "";
for(int i=0; i<ht; i++)
{
if (i%2!=0)
text = "YY" + text;
else
text = "XX" + text;
System.out.println(text);
}
}
And works with single for loop too!

Related

Creating a box in Java from user inputs, but how do I replace the interior of the box with a different input than its borders?

I need to create a box using user inputs. My inputs are the dimensions (height x width), the "interior" (the character that the box is filled with), and the "border" (the character surrounding the interior). I'm almost done, I believe; I can assemble the box given the dimensions and border, but I'm struggling to figure out how to fill the inside.
I don't know how to use decision statements to determine which characters belong on which line. If the current line is the first line, I want to print only border characters, or if the current character on the line is the first character in that line, print a border character, but print the interior for the following characters (until the end char), etc.
My code:
// Below this comment: import the Scanner
import java.util.Scanner;
public class Box {
public static void main(String[] args) {
// Below this comment: declare and instantiate a Scanner
Scanner scnr = new Scanner(System.in);
// Below this comment: declare any other variables you may need
int width;
int height;
char border;
char interior;
// Below this comment: collect the required inputs
System.out.println("Enter width : ");
width = scnr.nextInt();
System.out.println("Enter height : ");
height = scnr.nextInt();
System.out.println("Enter border : ");
border = scnr.next().charAt(0);
System.out.print("Enter interior : ");
interior = scnr.next().charAt(0);
// Below this comment: display the required results
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
}
}
As an arbitrary example, running my code with 7x5 dimensions and X and O characters gives me:
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
But my desired result would be:
XXXXXXX
XOOOOOX
XOOOOOX
XOOOOOX
XXXXXXX
Change:
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
To:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
if (j==0 || j==(height-1)) {
System.out.print(border);
}
else {
if (i==1 || i==width) {
System.out.print(border);
}
else {
System.out.print(interior);
}
}
}
System.out.println();
}
This could obviously be written in many different ways, some much more compact than this. I think this way is easy to understand, though...
For instance, here's a shorter version that works, but is harder to interpret:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
System.out.print(((j==0 || j==(height-1)) || (i==1 || i==width)) ? border : interior);
}
System.out.println();
}
You can certainly use if-else control structures to do this, but a simpler option would be to create the inner box with 2 rows and 2 columns fewer than the given dimensions, and then append the borders. You didn’t say what the expectation is for boxes of 1 or 2 rows only, so, you’ll have to handle those cases as well.
Also, for testability purposes, I’d create a method that accepts the dimensions as integers, and returns the box. You can then print the box in the main method. You can even take it one step further and create one method to create the inner box, and another to pad it with borders. Basically, try not to shove your entire project into one main method.
Implementation 1:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
if (args.length < 2) {
throw new IllegalArgumentException("Usage: java MyClass <rows> <cols>");
}
int rows = Integer.parseInt(args[0]);
int cols = Integer.parseInt(args[1]);
List<String> inner = createBox(rows - 2, cols - 2);
List<String> box = new ArrayList<>();
box.add("X".repeat(cols));
for (String row : inner) {
box.add("X" + row + "X");
}
if (rows > 1) {
box.add(box.get(0));
}
for (String row : box) {
System.out.println(row);
}
}
private static List<String> createBox(int rows, int cols) {
if (rows <= 0 || cols <= 0) {
return Collections.emptyList();
}
String row = "O".repeat(cols);
return Collections.nCopies(rows, row);
}
}
Implementation 2, slightly optimized:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
if (args.length < 2) {
throw new IllegalArgumentException("Usage: java MyClass <rows> <cols>");
}
int rows = Integer.parseInt(args[0]);
int cols = Integer.parseInt(args[1]);
int innerRows = rows - 2;
int innerCols = cols - 2;
String innerRow = innerRows > 0 && innerCols > 0 ? "O".repeat(innerCols) : "";
List<String> box = new ArrayList<>();
box.add("X".repeat(cols));
for (int i = 0; i < innerRows; i++) {
box.add("X" + innerRow + "X");
}
if (rows > 1) {
box.add(box.get(0));
}
for (String row : box) {
System.out.println(row);
}
}
}

Number pyramid, can't get numbers to print out to the left

I need a full pyramid but I can only get the right side of it. It is suppose to look like this with a example output of 4:
1
212
32123
4321234
I'm still new to java for loops so I've tried doing negative increments but that didn't work is there a type of method to print it in reverse?
import java.util.Scanner;
public class Pyramid {
public static void main(String [] args) {
System.out.println("Enter a number 1 to 15");
Scanner input = new Scanner(System.in);
int input1 = input.nextInt();
if (input1 >= 1 && input1 <=15) {
for(int column =1; column <input1; column++) {
for(int row = 1; row < column; row++) {
System.out.print(row + " ");
}
System.out.print(column);
System.out.println();
}
}
}
}
You need more loops, and you work row by row, and not col by col so the outer loop should use row.
And the inner loops are for :
print the spaces
print the numbers is descending order until 1 (exlude)
print the numbers is ascending order from 1
for(int row = 1; row <= input1; row++) {
for(int space = 0; space < input1-row; space++) {
System.out.print(" ");
}
for(int desc = row; desc > 1; desc--) {
System.out.print(desc);
}
for(int asc = 1; asc <= row; asc++) {
System.out.print(asc);
}
System.out.println();
}

Print out a string of characters from a 2D array into a certain number of rows

I'm trying to make a keypad in Java that takes letters input by the user, as well as a desired number of characters per row. It should then print the characters in the desired number of rows, so if "abcdefgh" is input and the desired row number is 4 it should print:
abcd
efgh
but I'm stuck on how to get it to work.
public class Keypad {
char [][] letters;
public Keypad(String chars, int rowLength) {
int counter = 0;
for (int i = 0; i<chars.length(); i++){
counter++;
}
letters = new char[rowLength][counter/rowLength];
}
public String toString() {
String s = " ";
for (int row=0; row<letters.length; row=row+1) { // Over rows
for (int col=0; col<letters[row].length; col=col+1) {
s = s + letters[row][col];
}
s = s + "\n";
}
return "the keypad is" + s;
}
the logic of the toString() method looks fine, but you didn't populate the letters array in the constructor. So you need to add something like this in the constructor:
public Keypad(String chars, int rowLength) {
// you don't need to count the length with a loop
int nRow = chars.length()/rowLength;
if(chars.length()%rowLength!=0) nRow++;
letters = new char[nRow][rowLength];
for(int i = 0, n = 0 ; i < letters.length ; i++) {
for(int j = 0 ; n < chars.length() && j < letters[i].length ; j++, n++) {
letters[i][j] = chars.charAt(n);
}
}
}

2D Array with Number Averages

Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;

how to automatically populate a 2d array with numbers

Hi i am trying to auto populate a 2d array based on user input.
The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array.
for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
But i am struggling to think of the right statement that will do this.
for the moment my code just prints out a 2d array containing *.
Has anyone any ideas how i could print out the numbers , i'm really stuck.
my code follows:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
Read n value,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.
int counter = 1;
for(int x = 0; x < num1; x++)
{
for(int y = 0; y < num2; y++)
{
grid[x][y] = counter++;
}
}
Afterwards you can output the array again with a double for loop.
I am not sure if I understand you right.
You have problem with the code printing *?
If yes, then the reason for that is this
System.out.print("*");
Should be
System.out.print(grid[row]);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int arraySize = input.nextInt();
System.out.println("Length: " + (arraySize*arraySize));
int[][] array = new int[arraySize][arraySize];
int count = 1;
for (int i=0;i<arraySize;i++) {
for (int j=0;j<arraySize;j++) {
array[i][j] = count;
if (j != (arraySize-1))
System.out.print(count + "-");
else
System.out.println(count);
count++;
}
}
}
This code should print out the numbers how you want them.

Categories

Resources