Trying to write a program that produces a kind of X/spiral pattern based on the width and the length that the user inputs. Length is how many characters across the screen and width is how many characters tall. I am having trouble figuring out the mathematical relationships to make the pattern I want happen.
Here is what a correct sample output would look like:
Input your desired length: 39
Input your desired width: 7
Here is the code I have so far and what it generates:
import java.util.Scanner;
public class Twisty {
public static void main(String[] args){
Scanner myScanner = new Scanner(System.in);
System.out.print("Input your desired length: ");
int length = myScanner.nextInt();
System.out.print("Input your desired width: ");
int width = myScanner.nextInt();
for(int i=0; i<width; i++) {
for(int j=0; j<length; j++) {
if(i==j || (i+j)%width==width-1 || (i+j)%width==0) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Input your desired length: 39
Input your desired width: 7
What am I doing wrong? Thanks for your help.
Concentrate on one X to start. You should only need to check 2 cases. One to draw one part of the X and the other to draw the other side. I basically grabbed this from your code and deleted the 3rd condition in your if statement.
//System.out.print("Input your desired length: ");
int length = 7;
//System.out.print("Input your desired width: ");
int width = 7;
for(int i=0; i<width; i++){
for(int j=0; j<length; j++){
if(i==j || (i+j)%width==width-1){
System.out.print("#");
}else{
System.out.print(" ");
}
}System.out.println();
}
After you get that behavior down and you can draw one X, then you just need to mod where you are horizontally with the width. Modding your length position with the width almost treats it like you are drawing a complete new X. You do not care where you are horizontally in respect to the whole picture but instead you care about where you are in respect to the current X you are drawing. You can do something like this:
//System.out.print("Input your desired length: ");
int length = 39;
//System.out.print("Input your desired width: ");
int width = 7;
for(int i=0; i<width; i++){
for(int j=0; j<length; j++){
if(i==j%width || (i+j%width)%width==width-1){
System.out.print("#");
}else{
System.out.print(" ");
}
}System.out.println();
}
Hope this helps.