Printing star and character triangle in java - java

Here is a screenshot of my Output and the desired output is located below as wellI have to create program that outputs a star and the letter o. I have gotten it working for the most part but the output is not 100% correct, minor things really. Here is my code so far:
for(int i = 1; i <=numRows; i++){
System.out.print("\n");
for(int j = 0; j<=numRows; j++){
if(i+j >= numRows){
System.out.print('*');
System.out.print("o");
}else {
System.out.print(" ");
}
}
System.out.println();
And here is a screenshot of what the output is supposed to look like

This is similar to what I had to do for class a long time ago. Here is the code:
for(int i = 0; i <= userInput/2; i++)
{
for(int j = 0; j < (userInput/2 - i); j++)
{
printDiamond = printDiamond + " ";
}
for(int k = 0; k <= (i*2); k++)
{
printDiamond = printDiamond + "*";
}
printDiamond = printDiamond + "\n";
}
**Reason it is userInput/2 is because the other half of the code prints the diamond in reverse, thus actually making a diamond and not a triangle. **
So what do we have: First inner loop is responsible for printing the white spaces that help give our diamond its shape. The next inner loop prints the top of the diamond; *2 because we want it to print the whole top of the diamond, and not just half of the diamond if we were to split it top to bottom.
I will leave the addition of the extra o's to you.

Related

Coding this pyramid pattern with user input and spaces in Java?

I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this!
I've made lots of pyramid patterns before, but this is one I can't figure out.
I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.
I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:
*
**
***
****
*****
So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.
This is the code (which gives a completely inaccurate output):
System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20.");
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
for (int j = 1; j == (num -= counter); j++)
{
System.out.print(" ");
}
for (int k = 1; k == counter; k++)
{
System.out.print("*");
}
System.out.println("");
counter++;
}
Please help! I feel so stupid.
I doubt your teacher will accept this. But it is just a one liner for fun
int num = 20;
IntStream.range(0, num).forEach(i -> System.out.println(String.format("%" + num + "s", new String(new char[i+1]).replace("\0", "x"))));
It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.
for (int i = 0; i < num; i++) {
for (int j = 0; j <= (num - counter); j++) {
System.out.print(" ");
}
for (int k = 0; k < counter; k++) {
System.out.print("*");
}
System.out.println("");
counter++;
}
it's pretty close mostly the for loop is wrong.
for(initialization;condition;increment)
the for loop only executes when the condition is true. In your case the conditions don't really make sense. Try changing it. also your counter and i are the same thing :)
Interesting coding exercise. You got it almost right anyway as others pointed out.
There are hundred ways to solve the problem.
Here is just a variation that saves a loop...
int lines=5;
for (int i=0; i<lines; i++) {
for (int k=0; k<lines; k++) {
System.out.print( (k < lines - i - 1) ? " " : "*");
}
System.out.println();
}
Another solution using a single (explicit) loop:
for (int i = 1; i <= num; i++) {
int expectedSpaces = num - i;
String spaces = repeat(" ", expectedSpaces);
String asterisks = repeat("*", i);
System.out.println(spaces + asterisks);
}
}
private static final String repeat(String toBeRepeated, int length) {
return new String(new char[length]).replace("\0", toBeRepeated);
}
As mentioned elsewhere, loop variables such as i usually start at 0 since such variables can be used as an array/List index. However, in this case there is no related array or List so sarting at 1 simplifies the logic.
I worked on something similar, this is what I did, you could give it a try. It takes a user input and displays spaces and "#"...
int size = n;
for (int i = 0; i <= size-1; i++){
for(int j = size -1; j > i; j-){
System.out.print(" ");
}
for(int j = 0; j <= i; j++){
System.out.print("#");
}
System.out.println();
}
The output would be:
#
##
###
####
#####
######

java nested loop logic for triangle's left side

Okay I am so tired of struggling with this and right off the bat I feel really stupid so please be gentle.. I've searched the stack overflow and web and still not finding anything. I am using a nested loop to create a triangle that looks like this:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
...etc. through 128 in the center column.
My loop for the left side renders to the right of my triangle instead of to the left. I'm pretty sure that after I receive an answer I will be hitting my head w/the palm of my hand and saying duh repeatedly. Anyway thanks for your help. I especially want an explanation of the logic. Here is the code.
public class Pyramid_center_x2_0519 {
public static void main(String[] args) {
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 1; j--) {
System.out.printf("%7s", "");
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
for (int leftSide = 2; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
System.out.println("");
}
}
}
Here is the way it renders:
Thanks again.......
UPDATED CODE 12 P.M. 5-31-16: I understand Java prints left to right. Below I have placed the left hand loop before the right side loop but my spacing in front of the triangle is not behaving. Thank you all... again
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 0; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
System.out.println("");
}
}
}
There is no way you can print left side after right and center side.
Java prints from left to the right.
(unless you use some arabic encoding)
Well, you already solved most of your Problems and your last updated version already prints the numbers correctly.
The only thing you still need to fix is the formatting to make it look nice.
Starting from your current code there are 2 things that need changing:
All your printed numbers are supposed to take up the same space (7). You already formatted your "right side" printed numbers in that way, all you have to do is do the same for the other numbers.
You currently allways add 8*7 spaces in front of the line, which of course isn't correct. If you look at the pyramid you can clearly see that 8*7 spaces is correct for the first line, but the second line would need 7*7 spaces in front, the third 6*7 etc. pp.
That means to get the correct formatting for you pyramid you have to modify your loop that prints the spaces to run 1 less time with each iteration of your main loop.
Here is one way how you could update your code to add those 2 changes (I added comments in front of the lines i changed as explanation):
public static void main (String[] args) throws java.lang.Exception
{
/** I added this counter to keep track
* of what iteration/line the loop currently is (see 2.)
*/
int iteration = 0;
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
/** Here we changed the loop condition
* from "j > 0" to "j > iteration"
* (So as iteration gets bigger, the loop runs less often)
*/
for (int j = 8; j > iteration; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
/** This should be self explanatory.
* You already did the same for rightSide.
* This will take care of 1.
*/
System.out.printf("%7d", leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
/** Here we increment our counter with each iteration aka line that is printed */
iteration++;
System.out.println("");
}
}
Try this
Edited: First try to put your spaces before putting your number in triangle(here my first inner for loop is doing) then apply some logic to print the number at its position accordingly.
static DecimalFormat df = new DecimalFormat("#");
public static void main(String[] args) {
for (int i = 1; i < 10; i += 2) {
for (int k = 0; k < (4 - i / 2); k++) { // first
System.out.print(" ");
}
for (int j = 0; j < i; j++) { // second
if (Math.pow(2, j) <= i)
System.out.print(df.format(Math.pow(2, j)));
else
System.out.print(df.format(Math.pow(2, i - j - 1)));
}
System.out.println("");
}
}
I think your approach is not good. Try this algorithm:
public class Main {
public static void main(String[] args) {
int levels = 8;
int lastLevelWidth = levels*2 + 1;
for (int i=0; i<levels; i++) {
int blankPositions = (lastLevelWidth - 1)/2 - i;
for (int j=0; j<blankPositions; j++)
print(" ");
int levelWidth = i*2 + 1;
int numberPositionsPerSide = (levelWidth-1)/2;
for (int j=0; j<numberPositionsPerSide; j++) {
print(Math.pow(2, j));
}
print(Math.pow(2, i));
for (int j=numberPositionsPerSide-1; j>=0; j--) {
print(Math.pow(2, j));
}
System.out.println();
}
}
public static void print(String string) {
System.out.print(string);
int spaces = 5 - string.length();
for (int i=0; i<spaces; i++)
System.out.print(" ");
}
public static void print(double n) {
print(Integer.toString((int)n));
}
}

For loop doesn't get finished

int length = Math.max(userOne.userName.length(), userTwo.userName.length());
length = Math.max(length, 5);
System.out.println("\nCurrent board:");
for (int i=0; i<3; i++) {
for (int s=0; s<3; s++) {
String box = "empty";
if (boxes[i][s] == 1)
box = userOne.userName;
else if (boxes[i][s] == 10)
box = userTwo.userName;
if (box.length() < length) {
for (int j=0; j<(length-box.length()); j++) {
box += " ";
}
}
System.out.printf("[%s]",box);
}
System.out.print("\n");
}
The third loop for (int j=0; j<(length-box.length()); j++) loops incorrect number of time!!
For example, when it's supposed to loop 3 times, it only loops 2 times; and when it's supposed to loop 8 times, it only loops 4 times. I tried to print j and it seems that the loop never gets finished.
I assume this has something to do with Java's synchronization, but I have no idea how to solve it!
With each iteration, you are both incrementing j and decreasing length-box.length() since you are adding to box, so the loop will only run half as many times as you want it to (rounded up).
A while loop makes more sense here:
while (box.length() < length) {
box += " ";
}
You increase the length of box inside your code - making your loop condition dynamic:
for (int j=0; j<(length-box.length()); j++) {
box += " "; //makes box.length() increase!
}
If you wanted to target the box length as it was before the loop, calculate it before the loop:
int targetLength = length - box.length();
for (int j=0; j< targetLength; j++) {
box += " ";
}
The box length changes during the loop and so your test changes.
Probably you need to save the initial box length in a variable and loop using that variable
int innerLength = length - box.length();
for (int j=0; j < innerLength; j++) {
box += " ";
}

Display triangle shape using asterisk using the substring method

I would like for my program to be in the shape of a triangle with space in between like the photo below.
Heres my code so far.
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String space= " ";
space.replaceAll("", " ");
int i = input.nextInt();
while (i > 0) {
for (int j = 0; j <1; j++)
System.out.print("*"+space.substring(0,0)+"*");
System.out.println();
i--;
}
}
when i run this code the output is this
**
**
**
**
**
**
**
**
**
I would like the output to look like this:
First of all your inner for loop doesn't serve any purpose. It runs only once. The logic would be same even if you remove it.
for (int j = 0; j <1; j++)
Secondly, I feel you wanted to do something like this :
System.out.print("*"+space.substring(i)+"*");
Make sure your string is big enough than the index i
String space= " ";
Scanner input = new Scanner(System.in);
int i=input.nextInt();
for (int j=0; j<(i-1); j++)
System.out.print(" ");
System.out.println("*");
for (int j=1; j<(i-1); j++)
{
for (int k=0;k<(i-1-j); k++)
System.out.print(" ");
System.out.print("*");
for (int k=0;k<(j*2)-1; k++)
System.out.print(" ");
System.out.println("*");
}
for (int j=0; j<(i*2-1); j++)
System.out.print("*");
System.out.println("");
Using something like String.format("%3s, "*") you can define the width (here: 3) and therefore the white-space of the output. If you add some clever code to define the width for each line, you can save yourself a lot of headaches.
In addition it is important to know that only a font with a fixed letter spacing will do the trick (like Currier New).

Java Homework - Printing a triangle pattern?

I'm struggling with an assignment. I understand that it is entirely my fault, but I've fallen behind in my classes and am struggling with this assignment.
My goal is to print the following pattern:
*
**
***
****
*****
******
*******
********
*********
**********
Using (nested) for loops.
Would anyone be able to give me hints on how I might go about this? I've managed to print a square of asterisks, but I'm having trouble figuring out how to make a triangle.
Thanks in advance for the help.
First figure out how many lines you need to print out. That's your first for loop. Then on each line, how many asterisks do you need to print out (suppose you are on line i, how many asterisks are on line i)? Answer those questions first and the program should come easily.
Review the following. It doesn't do exactly what you need to do but it will help get you started.
for (int x = 1; x <= 7; x++) {
for (int y = x; y <= 7; y++) {
System.out.print("(" + x + ", " + y + ")");
if (y == 7) {
System.out.print("\n");
}
}
}
Okay, so you basically have to print out as many asterisks as the line number, right?
I'm not allowed to give you code, as this is a homework assignment, but I can give you pseudocode.
start with variable i at 1, loop while i is less than or equal to 10, increment i
// The line of code that you just wrote will execute once per line.
// Now you can print out your asterisks.
// Make another loop and execute it once per asterisk. That's i times, right?
start with variable j at 1, loop while j is less than or equal to i, increment j
print out an asterisk
end loop
end loop
You need 2 loops for these type of problems . 1st loop is used for iteration and the second one for printing the stars. Here 1st u need to get the input from the user and store it in a variable suppose 'n' and the 1st loop should iterate till n .
for(i=1;i<=n;i++)
{for(j=1;j<=i;j++)
{ System.out.print("*");
}
System.out.println("");
}
java8 solution:
IntStream.rangeClosed(0, MAX)
.forEach(i -> IntStream.rangeClosed(0, i)
.mapToObj(j -> j == i ? "*\n" : "*")
.forEach(System.out::print)
);
here is an outline.
for (i = 1; i < 11; i++) {
String toPrint = "";
for (j = 1; j <= i; j++ {
// create string of asterisks here
}
// print a line here
}
since this is homework, you should do the rest yourself
Solution 1:
for(int i=1; i< 10; ++i) {
for (int j = 0; j<i; ++j) {
System.out.print("*");
}
System.out.println("");
}
Soulution 2:
String s = "*";
for (int i = 1; i< 10; i++) {
System.out.println(s);
s = s + "*";
}
Your choice.
class Program
{
static void Main(string[] args)
{
String var = "";
String exp_Str = "";
for (int i = 1; i < 8; i++)
{
for (int j = 1; j < i; j++)
{
if (i > j)
{
var = var + j;
//Console.WriteLine(j+"");
}
}
Console.WriteLine(var);
var = "";
}
Console.ReadLine();
}
}
use a for loop
for(i=0;i<10;i++){
for(int j=0;j<i;j++)
System.out.print("*");
System.out.println();
}
hope that helps!

Categories

Resources