Check if nested iterator variables sum to a certain number - java

I want to print an asterisk when i + j equals a specified number, but my code never prints one:
public class A{
public static void main(String[]args){
for (int i = 5; i < 10; i++) {
for (int j = 5; j < 10; j++) {
if ( i == j || ( i+j == 7 )) {
System.out.printf("*");
} else {
System.out.printf("");
}
}
System.out.println();
}
}
}

Well, when you are making the blank, it should be a " ", not a "", otherwise there will be no spaces. And it should be if I + J = 14, not 7, as it will never equal 7.

A good approach to drawing such patterns is to break them into regions/areas and then use various loops and conditional statements to construct those regions.
E.g. An approach to drawing X pattern is divide the X pattern into two parts from half vertically. Now, you can easily think to draw those to parts.
You can take help from this.
public class xpattern {
public static void main(String[] args) {
int totalLines = 11;
for (int i = 0; i < totalLines; i++) {
for(int j = 0; j < totalLines; j++) {
if(i == j || j == (totalLines - (i + 1))) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Related

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.

printing v shape in 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);
}
}

using java for loop with user input to make custom diamond

I am looking to make a diamond like this:
n=2
*
*$*
*
n=3
*
*$*
*$*$*
*$*
*
n=4
*
*$*
*$*$*
*$*$*$*
*$*$*
*$*
*
I can get the diamond with just * but cannot figure out how to add the $ in the mix
My code is as follows:
import java.util.Scanner;
public class ForNestedDemo
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("*$ ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
scan.close();
}
}
I agree that #GhostCat is the easiest way to go, but just for fun I figured it out using your way.
for (k = 1; k < (n + 1); k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
if(j == 0)
if(k == n+1)
System.out.print("*");
else
System.out.print(" *");
else{
System.out.print("$*");
}
}
System.out.println("");
}
for (k = 1; k < n; k++) {
for (i = 0; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
if(j == 0)
if(k == n+1)
System.out.print("*");
else
System.out.print(" *");
else{
System.out.print("$*");
}
}
System.out.println("");
}
I have fixed some of your errors and added some checks in there also.
The logic I have in place is:
If you are the first character, are you the middle row (k == n+1), if so, only print *, otherwise print _*.
If you are not the first character, print $*.
After that I just simply took my logic and pasted it down below in your lower half loop.
A simply way would be: instead of directly printing those "patterns", push them into string variables first - without thinking about $ signs. Just put the required spaces and *s into those strings.
Like:
" *"
" **"
"***"
Then, take those strings, and build the final strings from them: walk through each string, and when you find that str[index] and str[index+1] are '*' you simply put "*$" into your result string (otherwise you just copy the character at index).
Using that algorithm, the above strings turn into
" *"
" *$*"
"*$*$*"
And finally, you simply *copy** the upper lines down!
For the record: of course there are easy solutions that create the whole output in one shoot. But: you already got the loops in place that build lines that just miss the $ chars. So you can use my approach go get from your current code to a working solution easily.
You could do it as follows:
1. first print spaces
2. then print alternate '*' and '$' as per the order of the line.
public void printDiamonds(int n) {
//print the top part
for (int i = n-1; i > 0 ; i--) {
printDiamondLine(n, i);
}
//print the bottom part
for (int i = 0; i < n; i++)
printDiamondLine(n, i);
}
private void printDiamondLine(int n, int i) {
// i denotes the number of preceding spaces per line
for (int j=i; j>0; j--)
System.out.print(" ");
// print alternate * and $
for (int k=2*(n-i)-1; k>0; k--)
if (k%2==0)
System.out.print("$");
else
System.out.print("*");
System.out.println(); //print a new line at the end
}
Since this seems like homework, I normally wouldn't give the full code. But, the cat's out of the bag.
I would try to think of things in a simple mathematical manner and carefully look at the relationships between spaces, *s, and $s. When you do the code may come a little easier to write, simple, and cleaner.
There are always as many *s in a row as the row number
There are always one less as many $s as there are *s
There are always n - rowNum spaces in a row precedings the first character
There is a top, middle, and bottom to the shape based on these characteristics
Given that, I would start by writing a solution that would be easy to debug and very clean. The interesting part of my main would reflect the characteristics of the shape listed above:
printTop(1, 1, n);
printMiddle(n);
printBottom(n - 1, n - 1, n);
These methods would be defined as follows:
public static void printTop(int i, int j, int n) {
for (; n - j > 0; ++i, ++j) {
printLine(n - j, i);
}
}
public static void printMiddle(int stars) {
printLine(0, stars);
}
public static void printBottom(int i, int j, int n) {
for (; i >= 0; --i, --j) {
printLine(n - j, i);
}
}
The printLine() method prints a line/row of the shape given a number of spaces and *s. This is the part I would normally leave out but...
public static void printLine(int spaces, int stars) {
printSpace(spaces);
for (int i = 1; i <= (2 * stars - 1); ++i) {
if (i % 2 == 0) {
System.out.print('$');
} else {
System.out.print('*');
}
}
System.out.println();
}
I'm certain you can figure out what printSpace() is doing.
The benefit of this approach is it leads you towards what is inevitably going to be a primary goal of yours: decompose and modularize your code. This will become increasingly important as solutions become more complex. Good luck.
public static void main(String[] args) {
int n = 2;
int mid = (int) Math.ceil((n+n-1)/2.0);
String[] stringArray = new String[n];
for(int i = 0 ; i < n ; i++) {
StringBuilder sb = new StringBuilder();
for(int j = 2*i+1; j > 0; j--) {
if(j%2 == 0)
sb.append("$");
else
sb.append("*");
}
stringArray[i] = sb.toString();
}
for(int i = 0 ; i < n ; i++) {
for(int j = mid - stringArray[i].length()/2; j >0 ;j--) {
System.out.print(" ");
}
System.out.print(stringArray[i] + "\n");
}
for(int i = n-2 ; i >= 0 ; i--) {
for(int j = mid - stringArray[i].length()/2; j >0 ;j--) {
System.out.print(" ");
}
System.out.print(stringArray[i] + "\n");
}
}
Here you go. This code is not optimized in any way. Hope this gives you a general idea.

Printing special characters in a for loop instead of numbers

This is what the program is printing:
(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)
What I want it to do is to print ( * ) in replace of (1,1). I know an if statement is involved, but I'm having a hard time trying to figure out the condition I should put.
public class loops {
public static void main(String[] args)
{
int i=1;
for (int k = i-1; i< 4; i++)
{
int j =1;
for (int l = j-1; j < 4; j++)
{
if (k ==i+1 && l == j+1) System.out.print("( * )");
else System.out.print("("+k+","+l+")");
l++;
}
System.out.println();
k++;
}
}
}
The if condition is part of it, but you are also complicating your for loops, try this:
public class loops {
public static void main(String[] args)
{
for (int k = 0; k<3; k++)
{
for (int j = 0; j<3; j++)
{
if (k ==1 && j == 1)
{
System.out.print("( * )");
} else {
System.out.print("("+k+","+j+")");
}
}
System.out.println("");
}
}
}
you should just validate if both values are equal to 1 then print (*) , otherwise the result

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