How to reverse a string of numbers in a nested loop - java

This is a homework question so I would like help, not an answer.
I'm trying to create 2 triangles out of numbers based on a number entered by the user.
"Enter a number between 2-9: "3"
1
12
123
1
21
321
IE2:
"Enter a number between 2-9: "5"
1
12
123
1234
12345
1
21
321
4321
54321
I have been able to get the first triangle complete. But when I add my nested loop it messes up my first triangle with the numbers developed from the nested loop. It also puts all the numbers in a straight vertical line. I've tried variations for different nest loops and even tried messing with a StringBuilder, but was still unsuccessful.
Here's what I have in code so far:
import java.util.Scanner;
public class NestedLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a Number between 2-9: ");
int width = input.nextInt();
String r = "";
for (int i = 1; i <= width; i++)
{
r = r + i;
System.out.println(r);
}
}
}
Again, I'm looking for help/understanding and not just an answer.

There are two aspects the 2nd part of the question.
You need to generate strings with the numbers in the reverse order:
You could do this by adding the numbers at the other end.
You could do this by reversing the strings.
You need to arrange that there are spaces to the left.
You could do this by adding the required number of spaces to the left end of the string.
You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)
Or, you can build the string in a character array or string builder rather than using string concatenation.
The "trick" is to figure out what strategy you are going to use ... before you start cutting code.

try
int width = 5;
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// print numbers from 1 to current line number
for (int n = 1; n <= line; n++) {
System.out.print(n);
}
// end of line
System.out.println();
}
// add empty line between triangles
System.out.println();
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// printing padding spaces, number of spaces = with - line number
int nSpaces = width - line;
for (int i = 0; i < nSpaces; i++) {
System.out.print(" ");
}
// print numbers from number of current line to 1
for (int n = line; n >= 1; n--) {
System.out.print(n);
}
// end of line
System.out.println();
}

Can you just add another loop after your first loop like
String r = "";
String space = "";
for (int i = width; i >= 1; i--)
{
r = r + i;
System.out.println(r);
}
Try it. not yet tested

You need to use a queue.
eg. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html
Enque the numbers till you reach the max, and then start dequing them.
And while you dequeue, you need to apply the reverse
Queue<String> q = new LinkedList<String>();
for (int i = 1; i <= width; i++)
{
r = r + i;
q.add(r);
System.out.println(r);
}
while(!q.isEmpty()){
String j = q.remove();
//reverse j
System.out.println(reverse(j));
}
I leave the reversing part for you to do :)

public static void main(String[] args)
{
int n = 5;
for(int i=1; i<=n; i++)
{
for (int j=(n*2), k=n; j>1; j--)
{
if (k <= i)
{
System.out.print(k);
}
else
{
System.out.print('*');
}
k += (j)-1 > n ? -1 : 1;
}
System.out.println();
}
}

Just tried to implement in scala. Ignore if you don't like it..:-)
class Triangle extends App
{
val width = Console.readInt()
if (width < 2 || width > 9)
{
throw new RuntimeException()
}
var i, j = 1;
for (i <- 1 to width)
{
for (j <- 1 to i)
{
print(j)
}
print("\n")
}
for (i <- 1 to width)
{
for (dummy <- 1 to width-i)
{
print(" ")
}
for (j <- i to 1 by -1)
{
print(j)
}
print("\n")
}
}

Related

How do I change the position of my triangle?

am trying to do this triangle using 2 arguments.
Can someone help me out and see what is wrong with my code?
I can't seems to flip it to the same as this image.
Thank you!
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
for (int i = 0; i < height; i++) {
int starsThisLine = (int) Math.round(width * ((i + 1) / (double) height));
int dotsBeforeStars = Math.round((width - starsThisLine));
for (int j = 0; j < width; j++) {
if (j > dotsBeforeStars) {
System.out.print(".");
} else if (j < (dotsBeforeStars + starsThisLine)) {
System.out.print("*");
} else {
System.out.println(1);
Here is one way to do it. Just create a repeat method to return the String with the proper number of characters.
int height = 10;
for (int i = 0; i < height; i++) {
System.out.println(repeat("*", height-i)+repeat(".",i));
}
public static String repeat(String a, int count) {
StringBuilder sb = new StringBuilder();
while(count-- > 0) {
sb.append(a);
}
return sb.toString();
}
Both will print
**********
*********.
********..
*******...
******....
*****.....
****......
***.......
**........
*.........
One observation. Notice the first line has all stars. But that last line does not have all dots. The same was true in your patterns too.
If you want the start and finish to look like this:
**********
..........
The loop should be as follows:
for (int i = 0; i <= height; i++) {
If you want the start and finish to look like this:
*********.
*.........
The loop should be as follows:
for (int i = 1; i < height; i++) {
Assuming that the height and width will always be the same, here is an example implementation that uses a scanner (you can change this if you want to):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int dimensions = scan.nextInt();
for(int i = 0; i < dimensions; i++){
for(int dots = 0; dots < i; dots++){
System.out.print(". ");
}
for(int stars = dimensions; stars > i; stars--){
System.out.print("* ");
}
System.out.println();
}
}
}
In this example, our outer for loop with the dimensions represents the code for each row of the triangle, in this case, if we inputted 5, 5 rows.
Then, we start with printing dots since they are on the left side. Since the number of dots goes 0 -> 1 -> 2 -> 3 -> 4, this is equivalent to what "i", or our outer loop counter is.
With the stars, the number of stars goes 5 -> 4 -> 3 -> 2 -> 1, so if we just count backwards from the number of rows to our counter variable, we can get this number.

Printing spaces to align numbers according to my pyramid pattern

It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.

Java - How to create alternating triangle pyramid?

I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input. The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
The code I have written to achieve this is:
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
for (int j = 0; j < rows-i; j++){
System.out.print(star);
}
for (int k = 0; k <= i; k++){
System.out.print(circle);
}
System.out.println();
}
However, the output from my code does not match the pyramid above. The output of my code, with a user input of "6", is:
******o
*****oo
****ooo
***oooo
**ooooo
*oooooo
After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is. I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.
You could approach it another, far simpler, way.
In pseudo code:
create a String of n spaces
add "*" to it
loop n times, each iteration of the loop:
print it
replace " *" with "*O*"
This recognises a simple way to create the first line, and a simple way to create the next line from the previous line. Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.
Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).
A couple of ways to create a String of n spaces:
A loop that adds ' ' each iteration
new String(new char[n]).replace('\0', ' ')
How to replace certain characters of a String with other characters:
str = str.replace(" *", "*O*");
This method will work fine:
public void printPyramid (int input) {
for (int row = 1; row <= input; row++) {
for (int whitespace = input - 1; whitespace >= row; whitespace--) {
System.out.print(" ");
}
System.out.print("*");
for (int circle = 1; circle < row; circle++) {
System.out.print("o*");
}
System.out.println();
}
}
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
*o*o*o*o*o*o*
*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
Welcome to Stack Overflow!
First, the "o"s and "*"s are not alternating because the for loops execute until completion. This means the stars and circles will print out separately. For this application you only need one for loop and two if statements based on whether the "i" in the for loop is odd or even. An easy way to do this is with the modulo function :
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
if ((i % 2) == 0)
{
System.out.print(circle);
}
else
{
system.out.print(star);
}
System.out.println();
}
See if that works.
Thanks!
Here is a solution, easy to understand and friendly for beginners.
(If you want to go more advanced, look at the solution from #Bohemian♦ )
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
// How many "o" do we need?
int count_circle = i;
// How many * do we need?
int count_star = count_circle + 1;
// Let's create the string with o and *
String output = "";
for(int j = 0; j < (count_circle + count_star); j++){
if(j % 2 == 0) // if it is odd
output = output + star;
else // if it is even
output = output + circle;
}
// Do we need spaces at the beginning?
String spaces = "";
for(int j = 0; j < rows - i - 1; j++){
spaces = spaces + " ";
}
// Final output
output = spaces + output;
System.out.println(output);
}
Try this.
Scanner in = new Scanner(System.in);
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; ++i) {
System.out.printf("%" + (rows - i) + "s", "*");
for (int j = 0; j < i; ++j)
System.out.print("o*");
System.out.println();
}
Ex:
If rows=3
*##
**#
***
class Main{
public static void main(String x[]){
Scanner scan=new Scanner(System.in);
int rows=scan.nextInt();
for(int i=1;i<rows;i++){
for (int j=0;j<i;j++)
{
System.out.print("*");
}
for (int j=rows;j>i;j--)
{
System.out.print("#");
}
System.out.println();
}
}
}
See if that works.
Thanks!

Formatting Pascal's Triangle in Java

I've recently been teaching myself Java and I made a piece of code to produce Pascal's triangle. However, I can't get it to print out properly in a triangle. I can't figure out how to take into account numbers with multiple digits. Here's what I have so far:
public class Pas{
public static void main(String[] args){
pas(20);
}
public static void pas(int rows){
for(int i = 0; i < rows; i++){
String spaces = "";
int counter = (rows + 30)/2 - i;
for(int f = counter; f > 0; f --){
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++){
System.out.print( ncr(i, j) + " ");
}
System.out.println();
}
}
public static long ncr(int n, int r){
return fact(n) / (fact(r) * fact(n - r));
}
public static long fact(int n){
long ans = 1;
for(int i = 2; i <= n; i++){
ans *= i;
}
return ans;
}
Please keep in mind I'm a complete beginner and have never had any actual instruction. Everything I know is from the internet and messing around in Eclipse.
So the problem you're having is with spacing.
You are using always one space after a number, which is a problem because one number can be of length 1 - i.e: 1,2,3,4,5,6,7,8,9 - and another can be of length 5 - i.e. 31824. Because of that your triangle is wider on the right side.
To change that you have to reserve equal space for all your numbers - so if your biggest number is 184756 then for every number you print you have to reserve place for 6 digits and 1 empty space after them.
Also your initial spacing is not related to the number of rows, which in general can generate problems (if you would like to make triangle bigger than 30 - your current constant).
So there are two places where I would suggest changes:
First is this (1):
int counter = (rows + 30)/2 - i;
Here 30 is a constant that works for your 20 dimention triangle, but it's not elegant and won't work for bigger triangles. So I would suggest something like this (2):
int counter = (maxNumberLength*(numberOfRows - i))/2;
maxNumberLength is the maximum length the numbers in your triangle can get. How to calculate it? I'have estimated like that (3):
Math.pow(2d, numberOfRows.doubleValue());
This power will always be bigger than the biggest value in the triangle, but not by much. You can do it differently - it's first that came to my mind.
So back to (2)... the numberOfRows is the number of rows in the triangle. You substract i before multiplying to get the initial space maximumNumberLength/2 smaller in every row (so that it has a left slope).
The second thing that I would suggest changing is this:
System.out.print( ncr(i, j) + " ");
That's the most important part as you always add 1 space. If maximum number length is 6, then you should add 6 spaces after 1, 5 spaces after 20 and so on. Thats why I suggest creating a method that would return you the number of spaces you need (4):
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
In (4) you take number as first param (that's the number that is to be followed by spaces) and maxNumberLength from (3). This way all of your numbers would take the same amount of spaces in the output. I build the spaces with StringBuilder which is more effective for String concatenation.
So that's it - two changes and it should work.
I attach my full code so if you need you can test it:
public class TraingleTest
{
private final BufferedReader input;
private Integer numberOfRows;
public static void main(String args[])
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
new TraingleTest(input).run();
}
private TraingleTest(final BufferedReader input)
{
this.input = input;
}
private void run()
{
boolean validNumber = false;
System.out.print("Please enter number of rows for Pascals Triangle: ");
do
{
String usersInput = readUserInput();
validNumber = validateInput(usersInput);
} while (!validNumber);
makeTriangle();
}
private String readUserInput()
{
try
{
return input.readLine();
}
catch (final IOException e)
{
System.out.print("Error while reading input. Please try one more time: ");
return "";
}
}
private boolean validateInput(final String input)
{
try
{
Integer inputValue = Integer.parseInt(input);
if (inputValue > 2 && inputValue < 22)
{
numberOfRows = inputValue;
return true;
}
System.out.print("Value must be an integer between 3 and 21. Please insert valid number: ");
return false;
}
catch (final Exception e)
{
System.out.print("Error while parsing input. Please insert valid number: ");
}
return false;
}
private void makeTriangle()
{
int maxNumberLength = Double.valueOf(Math.pow(2d, numberOfRows.doubleValue())).toString().length();
for(int i = 0; i < numberOfRows; i++){
String spaces = "";
int counter = (maxNumberLength*(numberOfRows - i))/2;
for(int f = counter; f > 0; f --)
{
spaces += " ";
}
System.out.print(spaces);
for(int j = 0; j <= i; j++)
{
long number = ncr(i, j);
System.out.print(number + spaces(number, maxNumberLength));
}
System.out.println();
}
}
private String spaces(final Long number, final int maxNumberLength)
{
StringBuilder spaces = new StringBuilder("");
for (int i = 0; i<maxNumberLength - number.toString().length(); i++)
{
spaces.append(" ");
}
return spaces.toString();
}
public long ncr(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}
public long fact(int n)
{
long ans = 1;
for(int i = 2; i <= n; i++)
{
ans *= i;
}
return ans;
}
}
// I have not inputted the rows you can just give an input statement and input no of rows
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for(int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j = 0; j <= i; j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
this code will help you
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
The simplest thing to is to decree that every number you output will use a set number of characters, and to add extra blanks if necessary when outputting each number. For example, you can decide that each number will take 4 characters (if all the numbers are 9999 or less--actually, with Pascal's triangle with 20 rows, you'll need at least 5 characters). Then you'll need to adjust the number of spaces you print out in each row of the triangle.
To convert a number to a 4-character string where the number is pushed over to the right of the 4-character "box", and you add blanks on the left if necessary, use String.format:
String output = String.format("%4d", number);
If you want the number to be at the left of the "box",
String output = String.format("%-4d", number);
If you want the number to be centered in the "box", this is harder. Here's a method that will pad a string on both sides with blanks, making the padding as close to equal on both sides as possible:
public static String center(int desiredLength, String input) {
if (input.length() >= desiredLength) {
return input;
}
int leftPadding = (desiredLength - input.length()) / 2;
int rightPadding = desiredLength - input.length() - leftPadding;
StringBuilder result = new StringBuilder();
for (int i = 0; i < leftPadding; i++) {
result.append(' ');
}
result.append(input);
for (int i = 0; i < rightPadding; i++) {
result.append(' ');
}
return result.toString();
}
and then you could say
System.out.print(center(4, Integer.toString(number)));
or, if number is a long,
System.out.print(center(4, Long.toString(number)));
(P.S. Instead of StringBuilder, you could declare result to be a String and use things like result += " " like you did in your original question. That would work just as well, except maybe a few nanoseconds slower.)
package myjavapractice;
import java.util.Arrays;
import java.util.Scanner;
public class pascaltriangle
{
public static void main(String args[]) {
int i;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] pascal=new int[n][];
for(i=0;i<n;i++)
{
pascal[i]=new int[i+1];
}
pascal[0][0]=pascal[1][0]=pascal[1][1]=1;
for(int j=2;j<n;j++) {
pascal[j]=getNextRow(pascal[j]);
}
//print
for(int k=0;k<n;k++)
{
System.out.println(Arrays.toString(pascal[k]));
}
}
static int[] getNextRow(int[] p)
{
int[] current = new int[p.length];//row
System.out.println("length "+p.length);
current[0]=current[current.length-1]=1;//colmn
for(int m=1;m<current.length-1;m++)
{
current[m]=p[m]+p[m-1];
System.out.println("pof m is"+p[m]);
}``
return current;
}
}

How can I print a scalable pyramid in size determined with user input?

I'm taking a beginners Java course over the summer. I need to make a pyramid using loops for homework. The pyramid has to be made out of asterisks; in addition, size of pyramid is determined by user.
This is what I have for code now;
public class Pyramid {
public static void main(String[] args) {
int size = 6;
for (int x = 0; x < size; x++) {
for (int y = x; y < size; y++) {
}
for (int z = 0; z <= x; z++) {
System.out.print("*");
}
System.out.println("");
}
}
}
The problem of my code is that the number of asterisks in each row is wrong by one.
for (int z = 0; z <= x; z++) {
will execute the loop until z <= x is no longer true. That means it executes for z=0, z=1, z=2, ..., z=x--which means it actually executes the loop x+1 times. (The next z, z=x+1, is the first z that makes z<=x false.)
The normal idiom in Java (and other language with C-like for statements) is to start at 0 and use < when checking for the upper bound:
for (int z = 0; z < x; z++) {
You'll run into cases where you want to use <=, and you'll run into cases where you want to start at 1 instead of 0, but the majority of for loops with an integer index follow this form.
If I understand your question correctly :
public class Pyramid {
public static void main(String[] args) {
int size =6;
for (int i = 1; i <= size; i++) {
for (int x = size - 1; x >= i; x--) {
System.out.print(" ");
}
for (int y = 1; y<= i; y++) {
System.out.print("*");
}
for (int z= 1; z <= i - 1; z++) {
System.out.print("*");
}
System.out.println();
}
}
}
The output is :
*
***
*****
*******
*********
***********
If I understand your question, you could do something like this
int levels = 0;
Scanner input = new Scanner(System.in);
while (levels < 1) {
System.out.println("What size triangle would you like?");
if (input.hasNextInt()) {
levels = input.nextInt();
} else if (input.hasNext()) {
System.out.println("Not a valid size: " + input.next());
} else {
System.err.println("no more input");
System.exit(1);
}
}
for (int i = 1; i <= levels; i++) {
StringBuilder sb = new StringBuilder();
int t = i;
while (--t > 0) {
sb.append("*");
}
StringBuilder spaces = new StringBuilder();
for (t = 0; t < levels - i; t++) {
spaces.append(' ');
}
System.out.println(spaces.toString() + sb + "*" + sb);
}
To solve this problem it's best to think about the numbers that go into it...
*
***
*****
If you label the parts of the triangle
* row 1, 2 spaces, 1 star
*** row 2, 1 space, 3 stars
***** row 3, 0 spaces, 5 starts
Then you can just start playing with the numbers
The number of spaces to display is 3 - row # + 1
The number of stars to display is 2 * row - 1
Then construct a loop to draw each line.
within this loop, you need a loop to draw the number of spaces
and a loop to draw the number of stars

Categories