writiting the code with the appropriate variable values - java

I should Write a program Square.java that declares and initalizes a variable n (with n ≥ 2) and prints out a two dimensional n-by-n triangular pattern as shown below (where n=6).
public class Square {
public static void main (String[]args){
for (int Line=1; Line<= 6; Line ++){
for (int n=1; n<= (Line-1*1); n++) {
System.out.print ("# ");
}
for (int n=1; n<= (7-Line); n++){
System.out.print ("$ ");
}
System.out.println ("");
}
}
}
I can't manage to write the code with n>=6 or n=2

I am guessing you are forgetting to update the 7 when you change the 6. Put your size in a variable as shown below. Seems to work for me for 2 and any other size
public static void main(String[] args) {
int size = 6;
for (int Line = 1; Line <= size; Line++) {
for (int n = 1; n <= (Line - 1 * 1); n++) {
System.out.print("# ");
}
for (int n = 1; n <= ((size + 1) - Line); n++) {
System.out.print("$ ");
}
System.out.println("");
}
}

The size of the square must be an attribut of the class
The result :
public class Square {
public int size;
public Square(int size) {
this.size = size;
}
public void goSquare(){
for (int line=1; line<= size; line++){
for (int n=1; n<= (line-1); n++) {
System.out.print ("# ");
}
for (int n=1; n<= ((size+1)-line); n++){
System.out.print ("$ ");
}
System.out.println ("");
}
}
public static void main (String[]args){
Square square = new Square(6);
square.goSquare();
}
}

In your actual code 7-Line is what blocks values >=6 and for value =2 your code works great but it only prints one element(point).
Another thing if you use Line-1*1 you mean (Line-1)*1 which is equivalent to write Line-1.
Also in 7-Line the value 7 should be an attribute to be used in the first loop too in Line <= 7, you can see it in this working code:
int max = 2;
for (int Line = 1; Line <= max; Line++) {
for (int n = 1; n <= (Line - 1); n++) {
System.out.print("# ");
}
for (int n = 1; n <= (max - Line); n++) {
System.out.print("$ ");
}
System.out.println("");
}
And this is an Ideone Working Example of the code.

Related

Write a program that produces images of Christmas trees as output. I don't know what the error is

My code is resulting in an infinite loop when i run it. Don't know whats wrong.
!(https://d2vlcm61l7u1fs.cloudfront.net/media%2F1aa%2F1aa1af9f-41ff-48d8-89e9-7b093a909045%2Fphpbrt5Fy.png)
I have tried the code below. It compiles properly.
public class Project3_1 {
//declare SEGMENTS and HEIGHT
public static final int SEGMENTS = 4;
public static final int HEIGHT = 4;
public static final int TOTAL = (2*(SEGMENTS)) + (2*(HEIGHT)) - 3;
public static void TopTree(int SEGMENTS, int HEIGHT) {
for (int s = 1; s <= SEGMENTS; s++) {
for (int h = 1; h <= HEIGHT; h++) {
int ASTERISKS = ((2*s) + (2*h) - 3);
int SPACES = ((TOTAL - ASTERISKS)/2);
//spaces
for (int b = 1; b <= SPACES; b++) {
System.out.print(" ");
}
//Asterisks
for (int a = 1; a <= ASTERISKS; a++) {
System.out.print("*");
}
System.out.println();
}
}
}
public static void TreeBase() {
int x = (TOTAL - 7)/2;
for (int i = 1; i <= (TOTAL-1)/2; i++){
System.out.print(" ");
}
System.out.println("*");
for (int i = 1; i <= (TOTAL-1)/2; i++){
System.out.print(" ");
}
System.out.println("*");
for (int i = 1; i <= x; x++){
System.out.print(" ");
}
for (int i = 1; i <= 7; i++) {
System.out.print("*");
}
for (int i = 1; i <= (TOTAL - (x + 7)); i++) {
System.out.print(" ");
}
System.out.println("");
}
public static void main (String[] args){
TopTree(SEGMENTS, HEIGHT);
TreeBase();
}
}
Check your third for loop in TreeBase(), you increment the wrong variable. The code you posted runs fine for me, it just doesn't make that bottom line of asterisks due to that loop I mentioned not being correct. Once you fix that, you should be good

(Java Number Pyramid) How do I get my numbers to have more spaces between them while lining up accurately when it is an integer is > 9?

I am having difficulty getting the desired output. I know there are problems that are similar to mine that is already posted, but I find it hard to relate my code to their solutions without a massive overhaul.
The solution for my class assignment:
Supposed to continue until every direction of pyramid equals 1
My second method "spaces" is redundant and I am not sure why. Any help would be appreciated.
Blockq
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if(x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for(int i = 0; i<= 7; i++) {
for(int u = 0; u<spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for(int j = 0 ; j <i ; j++) {
System.out.print(""+ (int) Math.pow(2,j)+" ");
}
for(int k = i ; k >=0 ; k--) {
System.out.print(""+ (int) Math.pow(2,k)+" ");
}
System.out.println("");
}
}
}
I made every number take 3 places using String.format("%3s", (int) Math.pow(2, j)). You can make it dynamic by replacing the number 3 here with the length of the largest number you'll print. I also changed the number of spaces in your print statements. Here is the full code that prints an evenly spaced pyramid:-
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if (x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for (int i = 0; i <= 7; i++) {
for (int u = 0; u < spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for (int j = 0; j < i; j++) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, j)) + " ");
}
for (int k = i; k >= 0; k--) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, k)) + " ");
}
System.out.println("");
}
}
String.format explanation:-
String.format("%3s", str) will print the string str, padding it with spaces, to make the total length 3 if it's less than 3. Note that you can write anything instead of 3 - I used 3 because your biggest number was of length 3.
So "A" will be printed as "_ _ A" (2 spaces), and "Ab" will be printed as "_ Ab" (1 space).
I just replaced str with your Math.pow(2, j).

Array index out of bounds exception in java code

I am writing the code to print a matrix on taking user input in the form of n value:
Suppose if,
n= 3
output:
3 3 3
3 0 3
3 1 3
3 2 3
3 3 3
I am getting ArrayIndexOutOfBoundException in the line: a[i][j]=n;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. This is unlike C/C++ where no index of bound check is done. TheArrayIndexOutOfBoundsException is aRuntime Exception thrown only at runtime.
Look at this line:
for(int j=0;i<n;j++)
you increment while "i < n" but you increment "j++".
When your j reaches value 3, the inner loop continues, but exceeds the array-length (of 3, because the hightest array-index is actually 2).
(Also on a minor sidenote, it is usually preferrable to write ++i or ++j within for-loop increments. This is not a rule, just easier to read for most oldscool c-Devs). Also consider leaving spaces to inprove readability:
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][] = new int[n][n];
int b = 0;
int mid = n / 2 + 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i + j == mid) {
a[i][j] = n - b;
b++;
} else {
a[i][j] = n;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
minor correction in a loop
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
//System.out.println("Enter n");
int n = scan.nextInt();
System.out.println(n);
int a[][]= new int[n][n];
int b=0;
int mid = n/2 +1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++) //minor correction here
{
if(i+j==mid)
{
a[i][j]=n-b;
b++;
}
else
{
a[i][j]=n;
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}

Print a Z shape pyramid using * stars

I am trying to write a program that outputs a Z pattern that is n number of * across the top, bottom, and connecting line using for loops.
Example:
Enter a number: 6
******
*
*
*
*
******
This is my current code, it's producing a half pyramid upside down.
import java.util.*;
public class ZShape {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = n; y >= 1; y--) {
if (y > x) {
System.out.print("* ");
}
else
System.out.print(" ");
}
System.out.println();
}
}
}
This is the logic in the following code:
Loop over each row of the output (so from 0 to n excluded so that we have n rows)
Loop over each column of the output (so from 0 to n excluded so that we have n columns)
We need to print a * only when it is the first row (x == 0) or the last row (x == n - 1) or the column is in the opposite diagonal (column == n - 1 - row)
Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
if (row == 0 || row == n - 1 || column == n - 1 - row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Sample output for n = 6:
******
*
*
*
*
******
(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).
How about using three loops instead?
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println();
for (int x = n-3; x >= 0; x--) {
for (int y = x; y >= 0; y--) {
System.out.print(" ");
}
System.out.println("*");
}
for (int x = 0; x < n; x++) {
System.out.print("*");
}
public class Star {
public static void main(String[] args) {
for (int i = 0; i <=4; i++) {
for (int j = 0; j <=4; j++)
{
if (i==4 || (i+j)==4 || i==0)
{
System.out.print(" * ");
}
else
{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}
Here is a logic to print Z shape:
when i = 1, then the First line will print only "#"
when i = n, then the Last line will print in same way by "#" only
when i = j, that means it will execute one diagonal line by "#" only
Code:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
for (int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--) {
if (i == 1 || i == n || i == j) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}

Drawing a grid using nested loops

I am trying to draw a grid that looks like this:
1
12
123
1234
12345
123456
1234567
12345678
123456789
Here is my code:
public class shape {
public static void main(String[] args){
int number = 1, newNumber, zMax = 1;
String numString = "1";
for (int i = 1; i <= 9; i++){
for (int z = 0; z < zMax; z++){
System.out.print(numString);
number = number + 1;
numString += Integer.toString(number);
}
System.out.println("");
if (zMax <= 9)
zMax++;
}
}
}
It prints out something like this:
1
12123
121231234
12123123412345
etc
It is on the right track but I can't figure out what is going wrong... please help!
EDIT: Miss-understood the question, corrected it.
The reason your numbers repeat is your second loop. you either need to reinitialize numstring or reuse the old one and only add the new number.
public class shape { public static void main(String[] args){
String numString = "";
for (int i = 1; i <= 9; i++){
numstring = numstring + i;
System.out.println(numstring);
}
}
int start = 1;
int max = 10;
for(int i = 1; i < max; i++){
for(int j = 1; j <= i; j++){
System.out.print(j);
}
System.out.println("");
}

Categories

Resources