Java Graphical design loops - java

for(int i = 1; i < 12; i++)
{
for(int k=11; k > i; k--)
{
System.out.print("*");
}
System.out.print("\n");
}
I have the code above which displays a design like this:
**********
*********
********
*******
******
*****
****
***
**
*
I am wanting to swap it so that it looks like this:
**********
*********
********
*******
******
*****
****
***
**
*
I know that I need to use a loop and System.out.print(" ") in some way to leave spaces.
Whats the best approach to use? I created two separate loops, but with the next line commands this wont work in two loops. How would I integrate that into one loop?

For the second "picture": you'll have to print a variable number of spaces before the "*". That can be accomplished by using another loop before the loop that prints the "*", and knowing that every time you print a line, the number of spaces printed is incremented by one, and the number of asterisks is decremented by one.
EDIT :
Here's a hint, to get you started. Fill-in the blanks (and remove the comments):
int delta = /*fill*/;
for (int i = 0; i < /*fill*/; i++) {
for (int j = 0; j < /*fill*/; j++) {
System.out.print(" ");
}
for (int j = 0; j < /*fill*/; j++) {
System.out.print("*");
}
delta += /*fill*/;
System.out.print("\n");
}

Use String.format to left pad your string with spaces.

Do it using a 2-D array!!! Its very simple and efficient that way!!
For the second result:- Put '*' in places if row_no <= column_no (the half matrix above diagonal plus the diagonal elements) else put a space " " in other places. Run this in loops for row and column. Then print the 2-D array row wise.

Related

How can I repeat text in a manipulative way, and repeat this action until my target has been reached?

How do I count up from 1 to a given number in triangular fashion?
Attempt
while (numbers <= number) {
System.out.println(numbers);
numbers++;
}
Target Output
1
1 2
1 2 3
I recommend you read about looping in Java, this is a base to start from.
int num = 10;
for(int i = 1; i < num; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.print("\n");
}
This should provide the triangular structure you are looking for. Definitely do take a look at the link above. Since you are new to Java, you should take a walk through this code before simply copying it. Really try to see how it works and more importantly, why it works.

Printing arrays on single line in Java

I'm trying to make a 'histogram' in java and running into trouble with some formatting. I've got the below loop for printing a frequency distribution table:
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
System.out.println(asterisk);
freqTable = bins[i] + "\t";
System.out.println(freqTable);
}
But this produces an output like:
************
1-10
**********
11-20
**********
21-30
And i'd like to have it print like this:
1-10 ************
11-20 **********
21-30 **********
No idea how to get it to do this! Tried using toString(), didn't get anywhere though.
Thanks in advance!
You need to re-order the statements that print your items. I would recommend using a single println at the end of the loop:
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
System.out.println(bins[i] + "\t" + asterisk);
}
Simply change the order and using print instead of println
for (int i = 0; i < 10; i++) {
char asterisk[] = new char[frequency[i]];
Arrays.fill(asterisk, '*');
freqTable = bins[i] + "\t";
System.out.print(freqTable);
System.out.println(asterisk);
}
or alternative use System.out.printf
System.out.printf ("%s %s%n", freqTable, asterisk);
or a single System.out.println
System.out.println(freqTable + asterisk);

What is this Nested For Loop doing? (Asterisk Right Triangle)

I just started learning about "nested for loops". But my question what is the nested for loop exactly doing every time it loops? I'm still confused as to what is variable "i" is doing and what is variable "j" is doing. If you can explain what is happening after every loop, it would make nested for loops much clearer.
import java.util.Scanner;
public class LoopStatement {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numStar;
System.out.print("Number of stars: ");
numStar = input.nextInt();
while (numStar < 1 && numStar > 20) {
System.out.println("Enter a valid number ");
numStar = input.nextInt();
}
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
So this is the output I get if I input 4 for numStar
*
**
***
****
There is actually nothing special about nested loops, they behave exactly the same like regular loop.
Specifically here the outer loop loops from i being 1 to numStar and therefore prints numStar rows.
The nested loop loops from j being 1 to i where i is the number of current row being printed. In each iteration it prints one star and therefore altogether it prints i stars.
Therefore here it prints 1 star on row number 1, 2 stars on row number 2, etc.
Try writing down in a paper like this :
i=1 j=1 => *
i=1 j=2 => (j<=i) is false
.
.
i=2 j=1 => *
*
i=2 j=2 => *
**
.
.
You'll get the output if you try to write it in a paper.
In order to understand the nested loop you must understand the for structure. It sounds like you did not get it.
from the basics:
for (int i = 1; i <= numStar; i++) {
System.out.println(i);
}
the code above iterate exactly numStart following the steps:
a-Starts with i=1: int i = 1
b-Test condition: i <= numStar
c-Print the value of i in the screen: System.out.println(i)
d-increments i value: i++
It execute while the conditions is satisfied: i <= numStar. The steps c and d are executed only the condition is satisfied.
the tested loop follows the same logic:
for (int i = 1; i <= numStar; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
when i=1 -> j iterates from 1 to 1. So it prints "*"
when i=2 -> j iterates from 1 to 2. So it prints "**"
when i=3 -> j iterates from 1 to 3. So it prints "***"
and so on...
After the nested iteration finish there is line break: System.out.println();

how to print a number triangle in java

I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)  
{          
System.out.print(i); 
}      
System.out.print("\n");        
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){

Nest Loops, Cannot figure out how to code this

Hey I have a question I have been trying to figure out for a couple hours now, I need to use nested loops to print the following
-----1-----
----333----
---55555---
--7777777--
-999999999-
This is what I have so far.
public static void Problem6 () {
System.out.println("Problem 6:");
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= 9; j += 2) {
System.out.print(j);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
This is what it prints
-----13579-----
----13579----
---13579---
--13579--
-13579-
You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:
Which loop prints out the numbers?
The 2nd nested for loop.
What does it do?
It prints out j where j ranges from 1 to 9 and j is incremented by 2 each iteration of the loop. In other words, 1, 3, 5, 7, 9, which is confirmed in your output
What do you want it to do?
Well let's look at the desired output. You want 1 to be printed once on the first first line. You want 3 to be printed three times on the third next line. You want 5 to be printed five times on the fifth next line after that. And so on.
Do you notice a pattern? You want that loop we mentioned above to print the same number (1, 3, 5, ... i) as the number of times (1, 3, 5, ... i).
edit Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still 3 three times, 5 five times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.
Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.
These for loops
for(int i=1;i<=9;i+=2)
{
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
for(int b=9;b>=i;b-=2)
{
System.out.print("-");
}
System.out.println();
}
print
-----1-----
----333----
---55555---
--7777777--
-999999999-
public class pattern
{
public static void main ( )
{
for (int i = 1;i<=9;i+=2)
{
for(int b = 9;b>=i;b-=2)
{
System.out.print(" ");
}
for(int j =1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}

Categories

Resources