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.
Related
The loop causing issues is the second for loop.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; dataPoints[i] < controlValue; ++i) {
dataPoints[i] = dataPoints[i] * 2;
}
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
Currently when i run the test, this is what pops up.
Testing with inputs: 10 2 12 9 20
Output differs.
Your output
4 12 9 20
Expected output
4 12 18 20
the first number in the list of inputs is the maximum number it should multiply by 2. Since 20 is > 10, it is not multiplied. However 9 should be multiplying to 18, but it is not. If anyone could give some insight into anything i might be doing wrong when forming this loop, I would greatly appreciate it. Thank you!
Your second for loop is exiting because of the condition and the order of your input data, and will stop when a control value is reached. For example, if you instead had an input of 10 1 2 3 4, you would get the results you expect (ie. 2 4 6 8), but your for loop is exiting when the condition dataPoints[i] < controlValue is reached (in your case at 12).
Instead you should loop through the entire dataPoints array, as you do in your 3rd loop, and check the controlValue before doubling the values.
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int controlValue;
int i;
controlValue = scnr.nextInt();
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
}
for (i = 0; i < dataPoints.length; ++i) {
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
}
// This could be combined into the loop above...
for (i = 0; i < dataPoints.length; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
}
}
You could also do all of this in a single loop if you wanted to, for example:
for (i = 0; i < dataPoints.length; ++i) {
dataPoints[i] = scnr.nextInt();
if (dataPoints[i] < controlValue) {
dataPoints[i] = dataPoints[i] * 2;
}
System.out.print(dataPoints[i] + " ");
}
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.
I'm reading a book and before I go to next chapter, I want to solve every exercise from current one. I have a problem with creating this output (the number of rows must be between 11 and 20)
I almost have it, even when I think my code is pretty bad and I could get it in less lines.
public class piramide {
public static void main(String args[]){
int max, n;
max = 20;
n=1;
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
System.out.print(x);
x--;
if (x<0) x=9;
}
System.out.print("A"+n+"A");
for (int j=1; j<min; j++){
System.out.print(x2);
x2--;
if (x2<0) x2=9;
}
System.out.println();
n+=2;
}
}
}
This is my current code and this is the output:
0987654321A1A0987654321
21098765432A3A21098765432
432109876543A5A432109876543
6543210987654A7A6543210987654
87654321098765A9A87654321098765
098765432109876A1A098765432109876
2109876543210987A3A2109876543210987
43210987654321098A5A43210987654321098
654321098765432109A7A654321098765432109
8765432109876543210A9A8765432109876543210
The problem I'm having is that the left part of the pyramid should be reversed. For example in the first row it should start at 0 (from the A1A) and finish in 1 but it starts in 1 and finish in 0, any idea how can I turn it to the other side?
Thanks to all of you who helped me ^^.
Oh, and the caps A are just so I could find the number easier in the output.
Have you worked the problem out?
The code will be much easier to understand with a couple changes...
max, min, and especially the single letter variables like n should have names that help describe what they are. This may also help you think about the problem when you don't have to keep in mind what all those random letters mean.
n I will rename to rowIndex
max I will rename to totalRows
min I will rename to columnIndex
Starting with that we have
public static void main(String args[])
{
int totalRows = 20;
int rowIndex = 1;
int columnIndex = 1;
//we look ready to start at row 1, column 1!
}
Now, this section of your code:
for (int min=11; min<=max; min++){
if (n>9) n-=10;
int x=n-1;
int x2=n-1;
int b=min-1;
for (int j=1; j<min; j++){
while (b<max-1) {
System.out.print(" ");
b++;
}
You are setting min, or, the columnIndex, to start at 11, because that is the "middle" of the pyramid. Then you print out spaces to catch up to the columnIndex.
x = rowIndex - 1;
x2 = rowIndex - 1;
b = columnIndex - 1;
j and b are now like a second and third column index, which is catching up to the actual columnIndex
Look at this example of how your for loop works:
for (int j=1; j <min; j++) { // j = 1;
while (b<max-1) { // 10 < 19
System.out.print(" "); // print space
b++; // b = 11
// 11 < 19
// print space
// b = ...(*skip to the end*) 19
// j = 2
// b is still 19, doesn't print anything
// j = 3, etc.
}
System.out.print(x);
x--;
if (x<0) x=9;
}
In other words, j and b are unnecessary because we already have a columnIndex we can use. Let's do some more renaming of variables.
x I will rename to printValue
x2 will be unnecessary, we only need one printValue, However, I will be adding a totalColumns to the beginning of our main method.
So now our finished code will look like:
public static void main(String args[])
{
int totalRows = 20;
int totalColumns = (totalRows * 2) - 1; //added totalColumns, notice the number of columns increases by two with each row and we start with 1 column.
int rowIndex = 0;//easier for looping to start with zero
int columnIndex = 0;
int printValue = 0;
while (rowIndex < totalRows) // we will want to spin through every row
{
//notice there is no limit to the length of a variable name!
int numberOfValuesInRow = (rowIndex*2) + 1;
int numberOfSpacesToOffsetOnEachSide = (totalColumns - numberOfValuesInRow) / 2;
//Print Spaces before the numbers in this row
for (int i = 0; i < numberOfSpacesToOffsetOnEachSide; i++) //i is commonly used to stand for index in a single for loop
{
System.out.print(" ");
columnIndex++; //keep track of columnIndex so we know when we are at the middle of the columns
}
//Print numbers in this row
for (int i = 0; i < numberOfValuesInRow; i++)
{
if (columnIndex < (totalColumns/2) + 1) { //depending on columnIndex position, increase or decrease printValue
printValue++;
} else {
printValue--;
}
System.out.print(printValue%10); //Print printValue, the % will return the remainder of (printValue/10)
columnIndex++;
}
System.out.println(); //start next line
columnIndex = 0; //reset columnIndex for the next row
rowIndex++;
}
}
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
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")
}
}