printing v shape in java - java

I am a newbie to java programming and I am working on this excercise from my textbook. The goal is to print a V shape pattern of numbers. From the picture below, you can see what the output should look like. I am having trouble creating the other half of numbers. I have pasted my code down below for reference.
for (int i = 7; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int k = 1; k >= i*2; k++) {
System.out.print(" ");
}
System.out.println(i);

Use the following code (just made a few modifications to your code, did not check its efficiency):
public static void main(String[] args) {
for (int i = 7; i >= 1; i--) {
for (int k = 7; k >= i; k--) {
System.out.print(" "); // Print 7-i number of spaces before start of each line
}
System.out.print(i); // Print i
for (int j = 1; j <= i*2; j++) {
System.out.print(" "); // Print i*2 number of spaces after printing i
}
System.out.println(i); // Print i
}
}

Rather then nesting loops (and iterating backwards), I would decompose the generating of white-space with a method to repeat a given String a given number of times. Like,
private static String repeat(String s, int n) {
return Stream.generate(() -> s).limit(n).collect(Collectors.joining());
}
Then I would prefer a StringBuilder and a single call to println like
public static void main(String[] args) {
int start = 6;
for (int i = 0; i < start; i++) {
int v = start - i;
StringBuilder sb = new StringBuilder();
sb.append(repeat(" ", i)).append(v);
sb.append(repeat(" ", 2 * v)).append(v);
System.out.println(sb);
}
}

Related

How to hide characters using for loops, respectively?

I want to basically hide characters following three constant dots (...), the pattern goes like this:
Inputs a phrase from the user and outputs the phrase followed by three dots (...), then the phrase minus one character followed by three dots (...), then the phrase minus two characters followed by the dots, and so on until only one dot is left.
Note: This has to be done using nested for loops only
Sample input
1
disappear
Expected output:
disappear...
disappea...
disappe...
disapp...
disap...
disa...
dis...
di...
d...
...
..
.
This is my attempt:
Problem: I am unable to make it so the phrase decreases each time (minus 1 each time)
I tried using the charAt(); method, but it wouldn't work, I am sure that you would need a for loop separate for each of the dots or a whole set of dots, in this case.
import java.util.Scanner;
public class Dissappear{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
String phrase = keyboard.next();
if (option == 1){
for (int x = 0; x <= phrase.length(); x++){
System.out.print(phrase + "...");
for (int y = 0; y <= phrase.length(); y++){
char n = phrase.charAt(y);
System.out.print(n+"...");
}
}
}
}
}
This is how I got it to work:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
System.out.println(word.substring(0, originalLength - i) + "...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Without substring:
public class Disappear {
public static void main(String... args) {
String word = "disappear";
int originalLength = word.length();
for(int i = 0; i < originalLength; i++) {
for(int j = 0; j < originalLength - i; j++) {
System.out.print(word.charAt(j));
}
System.out.println("...");
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3 - i; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
You can do it with StringBuilder:
StringBuilder stringBuilder = new StringBuilder(str);
System.out.println(str + "...");
for (int i = 0; i < length; i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
System.out.println(stringBuilder.toString() + "...");
if (i == length - 1) {
for (int j = 0; j < 2; j++) {
for (int k = j; k < 2; k++) {
System.out.print(".");
}
System.out.println();
}
}
Ok! Nested for loops. But the outer one is only included to meet the requirement. Probably not in the spirit of the assignment though. Just keep decrementing k until it is zero and then latch it there until the StringBuilder length is 0 and the inner loop terminates.
StringBuilder sb = new StringBuilder("disappear...");
for (;;) {
for (int k = sb.length() - 4; sb.length() > 0;) {
System.out.println(sb);
sb.delete(k, k + 1);
k = k > 0 ? --k : 0;
}
break;
}

Can't figure out For Loop

I have recently started java, so I unfortunately am terrible at this. I have an question about a for loop question that was asked in my class today, but I can't figure out a part of it.
We were supposed to print out:
__1__
_333_
55555
with only for loops.
I have started the code but can't figure out what to do to print out the numbers, though I figured out the spaces.
public class Question{
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=?; k<=?; k??){
System.out.print(???);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
The question mark are the place where I don't know what goes in there.
Thanks.
You can do something like this,
class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 1; i <= 3; i++) {
for (j = 2; j >= i; j--) {
System.out.print("_");
}
for (k = 1; k <= (2 * i - 1); k++) {
System.out.print(i * 2 - 1);
}
for (j = 2; j >= i; j--) {
System.out.print("_");
}
System.out.println();
}
}
}
The first for loop will print the _ before the number, second one will print the number and 3rd one will print the _ after the number
The values are changing by two each time j increments, that leads to the formula 1 + (2 * (j - 1)) which is how you can finish your loops. Like,
for (int j = 1; j <= 3; j++) {
for (int i = 1; i <= 3 - j; i++) {
System.out.print(" ");
}
int n = 1 + (2 * (j - 1));
for (int k = 1; k <= n; k++) {
System.out.print(n);
}
for (int m = 1; m <= 3 - j; m++) {
System.out.print(" ");
}
System.out.println();
}
Outputs
1
333
55555
Thanks everyone for helping. I figured out the answer.
public class Welcome {
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=1; k<=(2*j-1); k++){
System.out.print(2*j-1);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
}
}
This can also be achieved as below
public class ForLoopPrinter {
public static void main(String[] args) {
int number = 1;
int row = 3;
int column = 5;
char space = '_';
for(int i = 1; i <= row; i++){
for(int j = 1; j <=column;j++){
int offset = (column - number)/2;
if( j <= offset ||
j > (number + offset)){
System.out.print(space);
}else{
System.out.print(number);
}
}
System.out.println();
number += 2;
}
}
}
Here number of For loops are limited to 2 (one for row and one for column).
Logic goes like this -
offset provides you number of spaces to be printed at both sides of number.
first if condition checks if j (position) is below or above offset and if true it prints underscore and if false it prints number
I know that right answer has been given for this question and it will work like charm. I just tried to optimise code by reducing number of For Loops in answers provided before. Reduction of For loop will improve performance.
Apart from reduction of For loops, this code has following advantage
- This code is more scalable. Just change row, column values (e.g. 5,9) or space char to '*' and check output. You can play with it.
I would suggest you to go with answer given by #Sand to understand For loop and then check this answer to understand how you can optimise it.

Pyramid pattern in Java using for loop

I want to print the pyramid pattern using word "Stream" by using for loop in Java. Please anyone can help me with this. I have printed pyramid with "*". I have also attached the program below:
Desired Result:
S
S t
S t r
S t r e
S t r e a
S t r e a m
What I have so far:
public class Pyramid
{
public static void main(String[] args)
{
System.out.println("-----Pyramid------");
int n = 5;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n - i; j++)
System.out.print(" ");
for (int k = 1; k <= 2 * i - 1; k++)
System.out.print("S");
System.out.print("\n");
}
}
}
This should work with any word.
As a hint I'd recommend to start loops with 0 instead of 1.
public static void main(String[] args) {
System.out.println("-----Pyramid------");
String word = "Stream";
int n = word.length();
for (int i = 0; i < n+2; i++) {
for (int j = 0; j <= n - i; j++)
System.out.print(" ");
for (int k = 0; k < i - 1; k++)
System.out.print(word.charAt(k) + " ");
System.out.print("\n");
}
}
Output:
-----Pyramid------
S
S t
S t r
S t r e
S t r e a
S t r e a m
You can use the charAt method in order to extract from the word Stream the chars you need inside the loop to create the pyramid
For example:
"Stream".charAt(0);
Will print the char S
"Stream".charAt(3);
Will print the char e.
More info here: String class reference

Java: Printing two dimensional array in grid format

I'm having difficulty figuring out the code to print a two dimensional array in grid format.
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.println(j);
}
System.out.println(i);
}
}
}
System.out.println(s) prints s, then prints a line return character. So if you want multiple print calls to end up on the same line, you should use System.out.print(s) instead.
Additionally, you can use System.out.println() (with no argument) to print nothing, but move to the next line. Bringing all of that together:
public class TwoDim {
public static void main (String[] args) {
int[][] ExampleArray = new int [3][2];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 2; j++){
ExampleArray[i][j] = i * j;
System.out.print(j + " ");
}
System.out.println();
}
}
}
When you use System.out.println(...);, it prints a newline char ('\n') after the string you intended to print. This should only happen if your line is over (i.e., outside the innest for statement). So, your for loops should be:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
ExampleArray[i][j] = i * j;
System.out.print(ExampleArray[i][j] + ' '); //You can replace ' ' by '\t', if
//you want a tab instead of a space
}
System.out.println("");
}
Hope that helps.

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories