I'm still working on my Java Diamond Problem.
Here is the current state of the diamond
I'm thinking the problem is the for loop right here,
all I need is for those spaces to be printed and then I'm finished.
Can anyone see any obvious reasons why the for loop I labeled with the problem isn't being entered or running?
//Bottom half of the diamond
int middleSpaces = sides + 2;
int downPreSpaces = 1;
int dRows = sides + 1;
for (int x = 1; x <= dRows; x++) {
if (x >= dRows) {
for (int z = 1; z <= sides + 1; z++) {
System.out.print(" ");
}
System.out.print("v");
}
if (x != dRows) {
for(int y = 1; y <= x; y++) {
System.out.print(" ");
}
System.out.print("\\");
//PROBLEM IS HERE
for (int e = middleSpaces - 2; e <= 0; e += 2) {
System.out.print(" ");
}
System.out.print("/\n");
}
Step through your code with a debugger and examine the state of the variables e and dRows at the location that is causing problems.
You were not decrementing middleSpaces also it was not initialized properly:
int middleSpaces = sides * 2; //NOTICE
int downPreSpaces = 1;
int dRows = sides + 1;
for (int x = 1; x <= dRows; x++) {
if (x >= dRows) {
for (int z = 1; z <= sides + 1; z++) {
System.out.print(" ");
}
System.out.print("v");
}
if (x != dRows) {
for(int y = 1; y <= x; y++) {
System.out.print(" ");
}
System.out.print("\\");
for (int e = middleSpaces - 2; e >= 0; e -= 1) {
System.out.print(" ");
}
middleSpaces-=2; //NOTICE
System.out.print("/\n");
}
middleSpaces - 2 might be less than dRows, or else one of the outer loops doesn't work.
Notice that the values of dRows, middleSpaces and dmSpaces do not change in the code you've shown. This means the inner loop in question will always print the same number of spaces.
You probably mean something like the following:
for(int e = middleSpaces - 2; e >= x; e -= 2) {
System.out.print(" ");
}
That might be off by one or something but is closer to the result you're trying to get.
Related
I just have one small issue with outputting a hyphen after every character (including the three dots shown in the code below)
Sample input
2 (option #)
disappear (phrase)
Expected output:
d-i-s-a-p-p-e-a-r-.-.-.
d-i-s-a-p-p-e-a-.-.-.
d-i-s-a-p-p-e-.-.-.
d-i-s-a-p-p-.-.-.
d-i-s-a-p-.-.-.
d-i-s-a-.-.-.
d-i-s-.-.-.
d-i-.-.-.
d-.-.-.
.-.-.
.-.
.
It outputs the "-" after every character excluding the last dot
I got the "-" to display after very word character but cant figure out displaying after the dots too, like it works but there has to be one less hypen:
My actual output:
d-i-s-a-p-p-e-a-r-.-.-.-
d-i-s-a-p-p-e-a-.-.-.-
d-i-s-a-p-p-e-.-.-.-
d-i-s-a-p-p-.-.-.-
d-i-s-a-p-.-.-.-
d-i-s-a-.-.-.-
d-i-s-.-.-.-
d-i-.-.-.-
d-.-.-.-
.-.-.-
.-.-
.-
I am partially done, I just need one less hyphen which would automatically also fulfill the requirement of not displaying a hyphen after the very last dot.
Code:
else if (option == 2){
for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
for (int a = 0; a < 3; a++){
System.out.print("."+"-");
}
System.out.println("");
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print("."+"-");
}
System.out.println("");
}
}
One way you could remove the last - is to only print - when it's not the last iteration. You can check that it's not the last iteration by checking loopVariable != loopBound - 1.
So your code would be:
for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
// You could just print the literal "--.-." instead
for (int a = 0; a < 3; a++){
System.out.print(".");
if (a != 2) { // Notice here!
System.out.print("-");
}
}
System.out.println();
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print(".");
if (i != 2 - j) { // and here
System.out.print("-");
}
}
System.out.println();
}
Here's how I would do it:
// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
for (int y = 0; y < phrase.length() + 3 - x; y++){
char n;
// Should we print the phrase or the dots?
if (y < phrase.length() - x) {
n = phrase.charAt(y);
} else {
n = '.';
}
System.out.print(n);
if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
System.out.print("-");
}
}
System.out.println();
}
I wrote some code that will print a diamond
static void printDiamond(int size) {
for (int i = 0; i < size; i++) {
for (int a = 0; a < (size - (i + 1)); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
for (int i = size-1; i >= 0; i--) {
for (int a = 0; a < (size - (i + 1)); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
}
The issue I'm having with the diamond is that it will print double for whatever I input. So, if the user were to input a 6 for the diamond, it should look like this:
XX
X X
X X
X X
X X
XX
With my code, if the user inputs 5, it prints out the following:
XX
X X
X X
X X
X X
X X
X X
X X
X X
XX
Instead of printing out 5 rows, it printed out 10. If I input 3, it will print out 6 rows instead of 3. It seems that for my diamond, it is outputting the number that it receives from the user, but then prints out that amount times 2. Is there a way I can half the size of what the printDiamond method outputs so it has the correct number of rows?
I was able to correct your code by tweaking the loop boundary conditions. First, you were printing the top portion of your diamond with a height of size and you were also printing the bottom potion with a height of size, for a total height of 2*size.
The other big problem was that you were not handling odd-numbered inputs, as all diamonds were coming out as even number height. I also corrected this problem. Have a look at the code below.
static void printDiamond(int size) {
for (int i = 0; i < (int)Math.ceil(size/2.0); i++) {
for (int a = 0; a < (int)Math.ceil(size/2.0) - (i + 1); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
for (int i = (int)Math.floor(size/2.0)-1; i >= 0; i--) {
for (int a = 0; a < (int)Math.ceil(size/2.0) - (i + 1); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
}
printDiamond(5);
System.out.print("\n");
printDiamond(6);
Output:
XX
X X
X X
X X
XX
XX
X X
X X
X X
X X
XX
When I run my code in my compiler, the second array is not printing for some reason even though it is essentially the same code for creating the first array copy and pasted. The first array does print.
Can someone tell me why the second array is not printing?
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n;
int i = 0;
int count = 0;
int x;
int d = 0;
int count2 = 0;
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
n = s.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
x = s.nextInt();
int[] bin = new int[8];
int[] bin2 = new int[8];
while (count < 8) {
bin[i] = n % 2;
i++;
n = n / 2;
count++;
}
System.out.print("First binary number: ");
for (int j = i - 1; j >= 0; j--) {
System.out.print(bin[j] + " ");
}
while (count2 < 8) {
bin2[d] = x % 2;
d++;
x = x / 2;
count2++;
}
System.out.print("\n\nSecond binary number: ");
for (int z = x - 1; z >= 0; z--) {
System.out.print(bin2[z] + " ");
}
}
Change your loop from
for (int z = x - 1; z >= 0; z--) {
To
for (int z = d - 1; z >= 0; z--) {
As in your earlier loop, x might have become 0 and you are trying to do like:
z = -1 and z >=0
in your for loop, which is why it doesn't enter the for loop.
In the first loop, you are counting down from i to zero. In the second loop, the equivalent of i is d.
But instead of counting down from d, you are counting down from x, which gives you the incorrect result. So change that do:
for (int z = d - 1; z >= 0; z--) {
System.out.print(bin2[z] + " ");
}
Change this
System.out.print("\n\nSecond binary number: ");
for (int z = x - 1; z >= 0; z--) {
System.out.print(bin2[z] + " ");
}
To
System.out.print("\n\nSecond binary number: ");
for (int z = d - 1; z >= 0; z--) {
System.out.print(bin2[z] + " ");
}
I want to create a pattern in java that looks something like this->
*
**
***
****
*****
****
***
**
*
(the number of stars depend on number entered by user.)
I know the first half half (increasing order), but please tell me how to make the rest half (decreasing order).
Thanks.
Here is my code for first part->
int y = Integer.parseInt(jTextField1.getText());
for (x = 0; x <= y; x++) {
jTextField2.setText(jTextField2.getText() + "*");
jTextArea1.append(jTextField2.getText() + "\n");
}
for decreasing order
for (x = y; x >= 0; x--) {
jTextField2.setText(jTextField2.getText() + "*");
jTextArea1.append(jTextField2.getText() + "\n");
}
You could use something like that:
int y = Integer.parseInt(jTextField1.getText());
for(x = y; x>=0; x--){
String s = "";
for(int i = 0; i < x ; i++) {
s += "*";
}
jTextField2.setText(s);
jTextArea1.append(jTextField2.getText()+"\n");
}
Note that if performance matters, you'd use a StringBuffer.
I assume you don't want to use external libraries. Guava's Strings.repeat woul be a better solution for your problem.
If you can use Guava, you could use this code:
int y = Integer.parseInt(jTextField1.getText());
for(x = 0; x<=y; x++){
String s = String.repeat("*", x);
jTextArea1.append(s+"\n");
}
for(x = y; x>=0; x--){
String s = String.repeat("*", x);
jTextArea1.append(s+"\n");
}
This solution is more straightforward, but it does require an external library
Try this code, i hope this will be use ful
int v = 1;
int totStars = 20;
for (int i = 1; i >= 0; i+=v) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
if(i >= totStars){
v = -1;
}
}
Here is a recursive solution which is worth taking the time to figure out how it works:
public void tristar(int n) {
tristar(n, "");
}
public void tristar(int n, String stars) {
if (n == 1) {
System.out.println(stars + "*");
} else {
System.out.println(stars + "*");
tristar(n-1, stars + "*");
System.out.println(stars + "*");
}
}
Hlo. Buddy.. try this code
int y = Integer.parseInt(jTextField1.getText());
for (x = 0,z=0; x <= (y+y-1); x++) {
if(x<=y){
z++;
}else{
z--;
}
for(int i=0;i<=z;i++){
jTextField2.setText(jTextField2.getText() + "*");
}
jTextArea1.append(jTextField2.getText() + "\n");
}
This will print the complete pattern
You are given a 2D array as a string and a word via keyboard. The word
can be in any way (all 8 neighbors to be considered) but you can’t use
same character twice while matching. Return word's first and last
character's index as (x,y). If match is not found return -1.
That's the question. I'm having trouble with searching. I tried that:
int x=0,y=0;
for(int f=0; f<WordinArray.length; f++){
for(int i=0; i<matrix.length; i++){
for(int j=0; j<matrix[0].length; j++){
if(matrix[i][j].equals(WordinArray[f])){
x=i; y=j;
System.out.print("("+x+","+y+")");
}
}
}
}
But, That code is not working as it is supposed to. How else I can write this searching code?
Referring to Sixie's code
Assuming this is a valid input/output to your program?
Size:
4x4
Matrix:
a b c d
e f g h
i j k l
m n o p
Word: afkp
(0,0)(3,3)
I edited your code, so that it should work for input on this form (it is case sensitive at the moment, but can easily be changed by setting .toLowerCase()
Scanner k = new Scanner(System.in);
System.out.println("Size: ");
String s = k.nextLine();
s.toUpperCase();
int Xindex = s.indexOf('x');
int x = Integer.parseInt(s.substring(0, Xindex));
int y = Integer.parseInt(s.substring(Xindex + 1));
System.out.println("Matrix:");
char[][] matrix = new char[x][y];
for (int i = 0; i < x; i++) {
for (int p = 0; p < y; p++) {
matrix[i][p] = k.next().charAt(0);
}
}
System.out.print("Word: ");
String word = k.next();
int xStart = -1, yStart = -1;
int xEnd = -1, yEnd = -1;
// looping through the matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
// when a match is found at the first character of the word
if (matrix[i][j] == word.charAt(0)) {
int tempxStart = i;
int tempyStart = j;
// calculating all the 8 normals in the x and y direction
// (the 8 different directions from each cell)
for (int normalX = -1; normalX <= 1; normalX++) {
for (int normalY = -1; normalY <= 1; normalY++) {
// go in the given direction for the whole length of
// the word
for (int wordPosition = 0; wordPosition < word
.length(); wordPosition++) {
// calculate the new (x,y)-position in the
// matrix
int xPosition = i + normalX * wordPosition;
int yPosition = j + normalY * wordPosition;
// if the (x,y)-pos is inside the matrix and the
// (x,y)-vector normal is not (0,0) since we
// dont want to check the same cell over again
if (xPosition >= 0 && xPosition < x
&& yPosition >= 0 && yPosition < y
&& (normalX != 0 || normalY != 0)) {
// if the character in the word is not equal
// to the (x,y)-cell break out of the loop
if (matrix[xPosition][yPosition] != word
.charAt(wordPosition))
break;
// if the last character in the word is
// equivalent to the (x,y)-cell we have
// found a full word-match.
else if (matrix[xPosition][yPosition] == word
.charAt(wordPosition)
&& wordPosition == word.length() - 1) {
xStart = tempxStart;
yStart = tempyStart;
xEnd = xPosition;
yEnd = yPosition;
}
} else
break;
}
}
}
}
}
}
System.out.println("(" + xStart + "," + yStart + ")(" + xEnd + ","
+ yEnd + ")");
k.close();
I think you need to plan your algorithm a bit more carefully before you start writing code. If I were doing it, my algorithm might look something like this.
(1) Iterate through the array, looking for the first character of the word.
(2) Each time I find the first character, check out all 8 neighbours, to see if any is the second character.
(3) Each time I find the second character as a neighbour of the first, iterate along the characters in the array, moving in the correct direction, and checking each character against the word.
(4) If I have matched the entire word, then print out the place where I found the match and stop.
(5) If I have reached the edge of the grid, or found a character that doesn't match, then continue with the next iteration of loop (2).
Once you have your algorithm nailed down, think about how to convert each step to code.
If I understood your question right. This is a quick answer I made now.
int H = matrix.length;
int W = matrix[0].length;
int xStart = -1, yStart = -1;
int xEnd = -1, yEnd = -1;
String word = "WordLookingFor".toLowerCase();
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (matrix[i][j] == word.charAt(0)) {
int tempxStart = i;
int tempyStart = j;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int k = 0; k < word.length(); k++) {
int xx = i+x*k;
int yy = j+y*k;
if(xx >= 0 && xx < H && yy >= 0 && yy < W && (x != 0 || y != 0)) {
if(matrix[xx][yy] != word.charAt(k))
break;
else if (matrix[xx][yy] == word.charAt(k) && k == word.length()-1) {
xStart = tempxStart;
yStart = tempyStart;
xEnd = xx;
yEnd = yy;
}
} else
break;
}
}
}
}
}
}
A little trick I used for checking all the 8 neighbors is to use two for-loops to create all the directions to go in:
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if(x !=0 || y != 0)
System.out.println(x + ", " + y);
}
}
This creates
-1, -1
-1, 0
-1, 1
0, -1
0, 1
1, -1
1, 0
1, 1
Notice: All but 0,0 (you don't want to revisit the same cell).
The rest of the code is simply traversing though the matrix of characters, and though the whole length of the word you are looking for until you find (or maybe you don't find) a full match.
This time the problem is that how could I print word's first and last
letter's indexes. I tried various ways like printing after each word
was searched. But, all of them didn't work. I am about to blow up.
int[] values = new int[2];
for(int i=0; i<matrix.length; i++){
for(int j=0; j<matrix[0].length; j++){
if(Character.toString(word.charAt(0)).equals(matrix[i][j]) == true || Character.toString(ReversedWord.charAt(0)).equals(matrix[i][j]) == true ){
System.out.print("("+ i + "," +j+")");
//First letter is found.Continue.
for(int p=1; p<word.length(); p++){
try{
for (int S = -1; S <= 1; S++) {
for (int SS = -1; SS <= 1; SS++) {
if(S !=0 || SS != 0)
if(matrix[i+S][j+SS].equals(Character.toString(word.charAt(p))) && blocksAvailable[i+S][j+SS] == true ||
matrix[i+S][j+SS].equals(Character.toString(ReversedWord.charAt(p))) && blocksAvailable[i+S][j+SS] == true) {
values[0] = i+S;
values[1] = j+SS;
blocksAvailable[i+S][j+SS] = false;
}
}
}
}catch (ArrayIndexOutOfBoundsException e) {}