Printing a word in a diamond format - java

My assignment is to print a word in the shape of a diamond like so:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
*e*******e
**d*****d
***i***i
****p*p
*****s
P.S. The asterisks are only there to show spacing, pretend one asterisk represent one space.
So far I have this:
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
//r*********r
//*e*******e
//**d*****d
//***i***i
//****p*p
//*****s
}
}
Which prints the first half of the diamond perfectly:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
The only part where I'm getting stuck is when I have to print the latter half of the diamond. Can anyone point me in the right direction? Please do not write the code for me, just try and give me some pointers based off the logic I've shown. Thank you.

Try to have only one loop. A very easy way to handle the "technicalities" of the problem is to work with an char array for the output. First you initialize it with the proper length, fill it with blanks (there is a library function for it), fill the two characters, and only then convert it to a String.
The only open question is where to put the characters, and I don't want (and should) to spoil that.
int fullLength = 2 * word.length() - 1;
for(int i = 0; i < fullLength; i++) {
char[] line = new char[fullLength];
Arrays.fill(line, ' ');
int k = ???;
char c = s.charAt(k);
line[word.length() - 1 - k] = c;
line[word.length() - 1 + k] = c;
System.out.println(new String(line));
}
Obviously, you want to calculate the position "from the middle" (so we have something like word.length() - 1 +- k), and for the first half of the word, k is equal to i.
Your task, should you decide to accept it, is to find out how to "bend k back" for the second half of the word.

import java.util.Scanner;
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
int wordLength2 = word.length();
int wordSize = word.length();
int wordLengthReverse = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
System.out.print(" " + word.charAt(wordLength2-2));
int spaceLength =((wordLength2*2)-1) -4;
int u =spaceLength -2;
for(int i =0; i < spaceLength; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordLength2-2));
System.out.println();
int m=3;
for(int num =2; num<wordSize-1; num++)
{
wordLength2 = num;
for(int i =0; i<num; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
for(int b = 0; b<u; b++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
System.out.println();
m++;
u = u-2;
}
for(int r =0; r<word.length()-1; r++)
{
System.out.print(" ");
}
System.out.print(word.charAt(0));
}
}
I have finished. This is my final code. I understand it is not as efficient as possible, or easy to follow, but it is flexible and not hard-coded, so I am content.

Related

How to Reverse an Int with For Loops

i am having trouble with reversing this code. what i am trying to have as
this is what i have so far but i can't seem to wrap my head around how the third for loop is supposed to be
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number + " ");
//number--;
}
System.out.println();
}
Before running your last loop you should store number in some temp variable:
int temp = number;
for(i = 0; i < c; i++) {
System.out.print(temp-- + " ");
}
As I said in the comment, you need to decrement the number but at the same time need to keep track of the highest values in a line to use it as a starting value in the next iteration. Something like this should work:
public static void main(String[] args) {
int rows;
int number = 0;
int highestValue = 0;
int i = 0;
rows = 5;
for (int c = 1; c <= rows; c++) {
number = highestValue; // reset number to the highest value from previous line
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
highestValue = number; // setting the highest value in line
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " "); // decrementing
}
System.out.println();
}
Do you have to implement this yourself, because otherwise there are tons of libraries handling arrays.
The steps you have to take are:
Find a way to read the input (integers) in a single line and store them in some kind of container (either an array, or a list).
You may have to isolate what a single integer is (e.g. "1 2 3" is 3 integers, which you want to reverse, while "12 3" is just 2, and you only want to reverse 2).
You need to ensure that your input is valid (e.g. a user may enter "1 a b c")
You need to flip the integers within the container or better copy the original container in reverse order. For this, you only need to iterate over the container's elements and add them to the target container in reverse order
for (Integer in : inputList) {
outputList.addFirst(in);
}
If you only want to print the integers, you don't have to store them in a list, you could just iterate over the container in reverse order.
It seems to bit a pattern program, you can add the number-- in you sysout
public static void main( String[] args )
{
Scanner input = new Scanner(System.in); //gets the users input
int rows;
int number = 0;
int i = 0;
rows = input.nextInt(); //takes the users input from console
while (rows <= 0) {
System.out.println("INVALID");
rows = input.nextInt();
}
for (int c = 1; c <= rows; c++) {
for (i = 0; i < c; i++) {
System.out.print(++number + " ");
}
for (int j = c; j < rows; j++) {
System.out.print("* * ");
}
for(i = 0; i < c; i++) {
System.out.print(number-- + " ");
//number--;
}
System.out.println();
}
}
Such type of pattern you can create through collections

My X's are being placed 1 space off in my histogram

import java.util.*;
public class HistogramGenerator {
public int getHeightOfHistogram(int[] occurences) {
// occurences = {1,0,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0]
int max = occurences[0];
for (int i = 1; i < occurences.length; i++) {
if (occurences[i] > max) {
max = occurences[i];
}
}
return max;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line: ");
String sentenceEntered = sc.nextLine();
System.out.println("Letter Histogram");
HistogramGenerator histogram = new HistogramGenerator();
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Map of all the characters
int[] occurences = new int[letters.length()]; //max size of all possible matches
// loop through sentenceEntered to find occurences of each character
for (int i = 0; i < sentenceEntered.length(); i++) {
int charValue = sentenceEntered.charAt(i);
int index = letters.indexOf(charValue); // index of the character we are searching for
if (index < 0)
continue;
occurences[index]++;
}
int heightOfHistogram = histogram.getHeightOfHistogram(occurences);
String[][] histogramArray = new String[heightOfHistogram][letters.length()]; //[2][26]
for (int j =0; j < occurences.length; j++) {
int numXtoInsert = occurences[j];
while(numXtoInsert > 0){
histogramArray[heightOfHistogram - numXtoInsert][j] = "X";
numXtoInsert--;
}
}
// print 26 dashes (length of letters)
for(int k=0; k < letters.length(); k++){
System.out.print("-");
}
System.out.println();
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print("");
continue;
}
System.out.print(histogramArray[row][col] + " ");
}
System.out.println();
}
System.out.println();
// print 26 dashes ( length of letters)
for(int u=0; u < letters.length(); u++){
System.out.print("-");
}
System.out.println();
// print all characters in letters
System.out.print(letters);
}
}
basically whatever word i put in it prints out something close to it, but not really correctly, if i type in apple for example it'll print out an X close to A, and X on P and an X close to P, and and X close to l and E.
maybe there's something wrong with the logic? I don't know, need some quick help!
The issue is with the printing logic. When you find a null value, you need to print a space. When you don't find a null value, you should not add an extra space. See below for the updated working logic:
// print histogram
for(int row =0; row < histogramArray.length; row++){
for(int col=0; col < histogramArray[row].length; col++){
if (histogramArray[row][col] == null) {
System.out.print(" ");
continue;
}
System.out.print(histogramArray[row][col]);
}
System.out.println();
}
System.out.println();

Making Tree with Nested Loops

So, for my programming class, our teacher tasked us with making a tree out of *'s and other random characters. There has to be a star at the top of the tree that increases in size every so often, depending how large the user wants the tree. For some reason, if the number the user enters is greater than 15, the bottom half is too far to the right. I tried changing my code, but then everything less than 15 is too far the right. How can I get that to work?
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int a = scan.nextInt();
int b = 0;
int c = 0;
int d = 0;
if ( a >= 12){
d = 1;
} else {
d = 0;
}
//Top Half of Star
for (int i = 0; i < a / 4; i++) {
for (int j = i; j < a; j++){
System.out.print(" ");
}
for (int j = 0; j < 2 * i + 1; j++){
System.out.print("*");
b = b + 1;
}
System.out.println("");
}
//Bottom Half of Star
for (int i = 1; i < a/4; i++){
for (int j = d; j < a; j++){
System.out.print(" ");
}
for (int j = c; j < b/3; j++){
System.out.print("*");
}
c = c + 2;
d = d - 1;
System.out.println("");
I think this is what you're looking for, if you're defining the size as the number of rows.
import java.util.Scanner;
public class NestedTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the size of the tree you would like");
int size = scan.nextInt(); // Get the size of the tree
for (int i = 0; i < size; i++) {
int spaces = size - i;
for (int s = 0; s < spaces; s++) { // Print spaces
System.out.print(" ");
}
for (int r = 0; r <= i; r++) { // Print stars
System.out.print("* ");
}
System.out.print("\n"); // new line
}
}
}

java for loop pyramid

I want to create a loop with a string so that with each successive loop, the last and first characters from the previous line will not be displayed. I'm also trying to print the length of each loop next to each line. It will look like an upside-down pyramid.
I had this:
for(int scounter = fullName.length(); scounter > 0; scounter--)
for (String name : fullName)
for(int counter = 0; counter < fullName.length(); counter++)
System.out.println(scounter + "[ " + fullName.substring(0, fullName.length() counter)+ " ]");
It prints something like this:
24******
24****
24**
24*
Yet I'm looking for something similar to this:
7*******
5*****
4***
1*
String str = "*******";
for (int i = 0, l = str.length(); i <= l/2; i++) {
String line = str.substring(i, l - i);
System.out.printf("%" + (i + 1) + "d%s\n", line.length(), line);
}
This will print:
7*******
5*****
3***
1*
I'm assuming you meant 3 instead of 4 in your example, that is, that you want to decrement by 2.
I started working on this problem and found my solution to be slightly different from Joao's. Hope this helps!
public class pyramid
{
public static void main(String[] args)
{
for(int i=0, sz=args[0].length();i<sz; ++i,--sz)
{
System.out.printf("%"+(i+1)+"d%s\n", sz-i, args[0].substring(i,sz));
}
}
}
Invocation as per request:
java pyramid abcdefg
7abcdefg
5bcdef
3cde
1d
java pyramid abcdef
6abcdef
4bcde
2cd
Your example does not match the words of your question, so here's a method that behaves according to your words as I understand them:
public void pyramid(String text) {
int len = text.length();
int start = 0;
while (start < len) {
for (int i = 0; i < start; ++i) {
System.out.print(" ");
}
System.out.println(text.substring(start, len));
++start;
--len;
}
}
for(int i = 1; i<=4; i++) {
for(int k = 3;k>=i; k--){
System.out.print(" ");
}
for(int j = 1; j<=i; j++){
System.out.print("*");
}
for(int n = 2; n<=i;n++){
System.out.print("*");
}
System.out.println(" ");
}
for(int m = 1 ;m<=3; m++){
for(int o = 1;o<=m; o++){
System.out.print(" ");
}
for(int p = 3;p>=m;p--){
System.out.print("*");
}
for(int q = 2;q>=m;q--){
System.out.print("*");
}
System.out.println();
}
}
}

Beginner in Java - Controlling output - Generating Asterix

I am having difficulties with completing this program. I am trying to make a program that creates asteriks, but then makes it into a triangle.
This is what I have already.
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
It is creating the asteriks, but how would I be able to continue them where they make a triangle... so they get bigger as they go, and then back smaller...
Thank you in advance!
Try moving
int spaces = n;
to AFTER the value of n is read from stdin.
This solves half your problem and hopefully gets you on the right track.
I added a few things to your code and got it to print the full triangle, where the number input in the scanner will be the number of asterisks printed in the bottom row. I.e. if the input is 3, the triangle will be two rows of 1->3; if the input is 5 then the triangle will be 3 rows of 1->3->5, and so on.
public static void main(String[] args) {
int ast;
int reverse = 1;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
int spaces = keyboard.nextInt();
for (int i = 0; i < spaces; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces) {
System.out.print(' ');
} else {
System.out.print('*');}
if (j > spaces + ast) {
for (int k = 0; k < spaces-(reverse-1); k++) {
System.out.print(' ');
}
}
int k = 0;
reverse++;
}
System.out.println();
spaces--;
}
}
}
I added another if statement after your if-else that triggers when the variable j exceeds the first loop condition. This triggers another loop that makes the output lines symmetrical by essentially repeating your first if statement.
I hope this helps =)

Categories

Resources