I have this task to display a pyramid as follows:
I wrote the code but unfortunately, the digits are displayed with spaces and order.
public class DisplayPyramid {
//main method declaration. Program entry point which begins its execution
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter an integer (number of lines)
System.out.print("Enter the number of lines: ");
int numbers = input.nextInt(); //Read value from keyboard and assign it to numberOfLines
String padding = " ";
//Display pyramid
//for loop to produce each row
for (int rows = 0; rows < numbers ; rows++) {
for (int k = numbers - rows; k >= 1; k--){
System.out.print(k + " ");
}
for (int l = 2; l <= numbers - rows; l++){
System.out.print(" " + l);
}
//Advance to the next line at the end of each rows
System.out.print("\n");
}
} }
And this is my output:
Can you help me figure out what is wrong with code ?
Anyone's help will be much appreciated.
Consider the 1st pass of the outer loop which produces
If we color hint your code, which the first inner loop in red, the second inner loop in green
This will be their corresponding output for each pass
The last pass of the red loop print "1 " and the first pass of green loop print " 2". They combine and become "1 2", which has 2 spaces in between.
The solution as Osama A.R point out, just reverse the printing order of number and space for the green loop and make if follow the red loop pattern. That will make the sequence neat.
Your second for loop prints the spaces first and then the number, however, the spaces have already been added by the first for loop, so just update the second for loop to print the spaces after printing the number.
E.g. your second loop should be like this:
for (int l = 2; l <= numbers - rows; l++){
System.out.print(l + " ");
}
Related
This is for an assignment, and is specifically requested. I know it seems somewhat pointless to create a nested for loop that only executes once, so wanted to clarify that.
The assignment question is a bit confusing to me, but states:
"Write a Java program that uses two nested FOR loops. The values used in the outer loop will be a user input value. The inner loop will use the input value divided by 2. Print a simple statement showing the values using the range of 1 to the user input number in the outer loop. The inner loop will print 1 to the divided result." However, the rubric states, "Student properly uses Java and creates a nested FOR loop and prints proper row and column number."
I initially thought I only needed to divide the input value by two and print that value, but now I feel like I'm supposed to print the input value in a simple row and column format? (If anyone else has clarity on this, please don't hesitate to drop a comment)
Basing my code on this, I'm having a really difficult time getting it to execute only once, and also having an issue printing a proper row and column. I'm attaching my attempt at the code below (this is an into-level course, fyi). Any feedback/help would be greatly appreciated!
import java.util.Scanner;
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
System.out.println(" \t1");
for (n = 0; n < 1; n++) {
for (n = 0; n < 1; n++) {
System.out.println("1 \t" + n);
}
System.out.println();
}
}
}
I think he meant that the outer for loop should run till n ( value entered by user ) and inner for loop will run till n/2 ( divided value )
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
// System.out.println(" \t1");
int val = n/2;
for (int i = 1;i<=n; i++) {
// printing from range 1 to n in the outer loop
System.out.print(i);
for (int j = 1; j<=val; j++) {
// printing from 1 to divided value in the inner loop
System.out.print(" \t" +j);
}
System.out.println();
}
}
}
When you run it , it gives output in this format .
Right now you are accepting the value from the user in the variable n and then later changing it to 0 in the loop. Doing this you are loosing the input you took from the user. You won't be able to calculate the n/2 if you loose what you accepted from the user in the first place.
You'll have to define different variables/counters for your two loops. Your outer loop will go from 1 to the number you accepted and the inner one will go from 1 to the half of the number you accepted from the user.
Your final code should look something like this (for illustration purposes only):
import java.util.Scanner;
class rowCol {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
sc.close();
for (int row = 1; row <= n; row++) {
// Print Row Number
System.out.print("Row: " + row + "\t");
for (int col = 1; col <= n/2; col++) {
// Print Column Number
System.out.print("Column: " + col + "\t");
}
// Print New Line
System.out.println();
}
}
}
Okay, I'm making a program that'll make vertical lines, horizontal lines, diagonals lines too! I'm kinda confused on one of my outputs that doesn't make any sense.
So my psudocode was like this:
//enter a char
//enter a number that will determine how long the line is
//define with easyreader what type of line it will be (hori, vert, diag)
//the idea of making the diag lines was this...
#
(two spaces) #
(four spaces) #
(six spaces) #
//we could use the sum spaces = spaces + 2; to keep on calculating what
//the previous spaces was
Code was:
class starter {
public static void main(String args[])
{
System.out.print("What char would you like? ");
EasyReader sym = new EasyReader();
String chars = sym.readWord();
System.out.print("How long would you like it to be? ");
int nums = sym.readInt();
System.out.print("Diag, Vert, or Hori? ");
//you want to read the __ varible, not the sym.readX()
String line = sym.readWord();
System.out.println("");
System.out.println("");
if(line.equals("Hori")){
for(int x = 0; x < nums; x++){
System.out.print(chars + " ");
}
}
else if(line.equals("Vert")){
for(int y = 0; y < nums; y++){
System.out.println(chars + " ");
}
}
else{
for(int xy = 0; xy < nums; xy++){
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}
}
}
}
}
At the bottom you will see a for loop called xy that will read how long the lines would be. Under that for loop would control the spaces. However, for some reason, the sum isn't updating correctly. The output is always:
2 (char)
5 (char)
8 (char)
2 (char)
5 (char)
8 (char)
...
The output should be:
2 (char)
4 (char)
8 (char)
...
EDIT **********
Since I need help now changing incriements here is an example (So I don't have to explain it a lot in comments)
Example: If user puts he wants the line as much as 5 units. With two for loops, one controlling how many spaces he wants, one controlling how many chars will print out, the output would be then 2, 4, 6, 8, 10.
In for loop statement, you say 'increase spaces by one after each iteration' (spaces++):
for(int spaces = 0; spaces < nums; spaces++){
In the body of your loop, you additionally ask to increase it by 2:
spaces = spaces + 2;
So each iteration it gets increased by 3.
By the way, there seems to be something wrong with your nested loops (if I understand the intention correctly). If the outer loop (looping over xy) draws a line on each iteration, then the inner loop, which is supposed to output an indent for the current line, must be bounded by xy (multiplied by 2) rather than nums. I'd write it like this:
for (int xy = 0; xy < nums; xy++) {
for (int spaces = 0; spaces < xy*2; spaces += 2) {
System.out.print(" ");
}
System.out.println(chars);
}
Because you are adding 3 to the spaces each time
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
spaces++ spaces += 1
spaces = spaces + 2; spaces += 2
actually the problem is in this part :
for(int spaces = 0; spaces < nums; spaces++){
spaces = spaces + 2;
System.out.print(spaces + " ");
System.out.println(chars);
}
when the program starts we have spaces = 0
then this part is going to run spaces =spaces + 2
now spaces is equal to 2, so we have spaces = 2
the program prints 2, after that spaces increments by 1 using spaces++ part
now spaces is equal to 3, which means spaces=3
after that this line is going to be run spaces = spaces + 2
so the value of spaces becomes 5
and if we do this for ever and ever we will have this sequence of numbers :
2 5 8 11 14 ....
in fact this is because we are incrementing spaces by 3 in each iteration
if you modify your code in this form, the problem is going to be solved :
for (int xy = 0; xy < nums; xy++) {
for(int spaces = 0; spaces < xy*2; spaces += 2)
System.out.print(spaces + " ");
System.out.println(chars);
}
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++){
My programming assignment was to print an array with 10 random integers and then have 4 lines with different outputs (every even element, reverse order, etc.)
The code itself works fine (as far as I can tell) but one problem I'm having is that I had to put a System.out.println(""); before every line in order for the lines to look correct.
Initially, when I had it System.out.println("[LINE 1]....") *for loop * System.out.print("arr[i] + ", ") *close for loop * it printed each integer on a separate line instead of all on one line. Am I missing something here?? Can anyone help?
Here's my code:
import java.util.*;
public class RandomInteger {
public static void main(String[] args){
Random random = new Random();
int arr[]=new int[10];
System.out.print("The array of random numbers: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(50);
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 1] Elements at an even index: ");
for (int i = 0; i < arr.length; i++) {
if(i%2==0){
System.out.print(arr[i]+" (at index "+i + "), ");
}
}
System.out.println("");
System.out.print("[LINE 2] Every even element:");
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0){
System.out.print(arr[i] + ", ");
}
}
System.out.println("");
System.out.print("[LINE 3] Elements in reverse order: ");
for(int i=arr.length-1;i>=0;i--){
System.out.print(arr[i] + ", ");
}
System.out.println("");
System.out.print("[LINE 4] First Element is: "+arr[0]+" and Last ELement is: "+arr[arr.length-1]);
}
}
All overloads of the println method append a newline following whatever you want to print; all overloads of the print method don't.
If all you want is a newline, then you don't even have to supply an argument -- call the no-argument println overload.
System.out.println();
Can you try with this exemple:
System.out.print("\n[LINE 2] Every even element:");
You have write \n because it is a simple way to introduce a newline although the right way isn't with system.out.print, the right way to this format is system.out.format like to c lenguage, but also used
I guess you want to remove the code System.out.println("").
use "\n"
You can change System.out.print("[LINE 1] Elements at an even index: ") to System.out.print("\n[LINE 1] Elements at an even index: ").
I have a question about the third for loop, how does it work please ?
public void outputBarChart()
{
System.out.println("Grade Distribution: \n");
int frequency[] = new int[11];
for(int oneGrade : grade)
{
++frequency[oneGrade / 10];
}
for (int count = 0; count < frequency.length; count++)
{
if (count == 10) {
System.out.println("100");
}
else {
System.out.printf("%02d-%02d: ",
count*10, count*10 + 9);
}
//the third for loop here !
for (int star = 0; star < frequency[count]; star++){
System.out.print("*");
}
System.out.println();
}
}
The problem is I don't know the mechanics how it print out stars.
Well lets go through the code then:
The second for loop which contains the third for-loop will loop 11 times since thats the length of frequencey. Okay that was easy.
Now the third for-loop iterates frequency[count] times, we don't know this value, but we know that it is an integer. So what third loop will do is simply to print out a star frequency[count] times. After that we're done with the third loop and a newline is printed by the second loop.
System.out.println("*" * frequency[count]);
The loop will take the variable star and loop and increment until it reaches the value of frequency[count]. So it will run the loop the same number of times as the value stored in frequency[count].
Each loop iteration it prints a star. At the end it prints a blank line.
The result is printing the number of stars as frequency[count] on a line.