Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I recently wrote some code that is supposed to make a string into a box.
If the input is "hello", The output should look like this:
hello
e l
l l
l e
olleh
I have pretty much all of the code and I made it into a box, except I can't seem to make the letters line up. I know the part where I messed up, I just don't know how to fix it. The part that is messed up is in quotations and is commented. Here is the code, Thank you!:
int num = 0;
for (int i=1;i<=word.length();i++){
for (int a=1;a<=word.length();a++){
if(i>1 && i<word.length() && a>1 && a<word.length())
System.out.print(" ");
else
//"System.out.print(word.charAt(num));
}
System.out.println("");
}
You could have your String reversed first, and store it in a char[] array. (As I forgot to use StringBuilder#reverse()).
You can then iterate with 2 for loops as you did, with some conditions for the top, bottom and middle lines as follows:
The trick is using the original string for the top and left part and the reverse one on the right and bottom one.
Also note that you're starting from index 1~word.lenght() and this is not what you want since when printing each character you start from index 0 not 1
public class WordSquare {
public static void main(String[] args) {
String word = "hello";
int num = 0;
char[] reverseWord = new char[word.length()];
int counter = 0;
for (int i = word.length() - 1; i >= 0; i--) {
reverseWord[counter] = word.charAt(i);
counter++;
}
for (int i = 0; i < word.length(); i++) {
counter = 0;
for (int j = 0; j < word.length(); j++) {
if (i == 0) {
System.out.print(word.charAt(j));
} else {
if (j == 0) {
System.out.print(word.charAt(i));
} else if (j < (word.length() - 1)) {
if (i < (word.length() - 1)) {
System.out.print(" ");
} else {
System.out.print(reverseWord[j]);
}
} else {
System.out.print(reverseWord[i]);
}
}
}
System.out.println("");
}
}
}
Which produces:
hello
e l
l l
l e
olleh
I just assumed that you had to do it inside the two for loops so I just added to the loop.
for (int i = 0; i <= word.length() - 1; i++){
for (int a = 0; a <= word.length() - 1; a++){
if(i > 0 && i < word.length() - 1 && a > 0 && a < word.length() - 1) {
System.out.print(" ");
} else if(i == word.length() - 1) {
System.out.print(word.charAt(word.length()-1-a));
} else if(a != word.length() - 1) {
System.out.print(word.charAt((a+i)%word.length()));
} else {
System.out.print(word.charAt((a-i)%word.length()));
}
}
System.out.println("");
}
Here's the same thing in only two else statements
for (int i = 0; i <= word.length() - 1; i++){
for (int a = 0; a <= word.length() - 1; a++){
if(i > 0 && i < word.length() - 1 && a > 0 && a < word.length() - 1) {
System.out.print(" ");
} else if (a == 0 || i == 0) {
System.out.print(word.charAt((a+i)%word.length()));
} else {
System.out.print(word.charAt((2*(word.length()-1)-a-i)%word.length()));
}
}
System.out.println("");
}
String word = "hello";
System.out.println(word);
for (int i = 1; i < word.length() - 1; i++) {
System.out.print(word.charAt(i));
for (int j = 0; j < word.length() - 2; j++) {
System.out.print(" ");
}
System.out.println(word.charAt(word.length()-i-1));
}
System.out.println(new StringBuilder(word).reverse().toString());
Output:
hello
e l
l l
l e
olleh
Try this, More Simpler logic
public class SchoolAssignment
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
String input = "hello";
String middleSpaces = null;
//Determine amount of space in middle rows
StringBuilder middleSpace = new StringBuilder();
middleSpace.append("%");
middleSpace.append(String.valueOf(input.length()-2));
middleSpace.append("s");
middleSpaces = String.format(middleSpace.toString(), " ");
//print first line
System.out.println(input);
//print middle lines
for(int i = 1; i <= input.length() - 2; i++){
StringBuilder middleLine = new StringBuilder();
middleLine.append(input.charAt(i));
middleLine.append(middleSpaces);
middleLine.append(input.charAt(input.length() - 1 - i));
System.out.println(middleLine.toString());
}
//print last line
StringBuilder lastLine = new StringBuilder();
lastLine.append(input);
lastLine=lastLine.reverse();
System.out.println(lastLine);
}
}
Try this
public void print(String word){
System.out.println(word);
for (int i=1;i<word.length()-1;i++){
System.out.print(word.charAt(i));
for (int j=0;j<word.length()-2;j++){
System.out.print(" ");
}
System.out.println(word.charAt(word.length()-i-1));
}
System.out.println(new StringBuilder(word).reverse().toString());
}
Interesting homework question btw
Related
I have to write a code as a task for my university and we have to recreate Minesweeper with java and it has to be runned in the command line.
For the matchfield we have to make an array that looks in the end like this picture:
Example how it sould look in the end
And to choose the field we have to use the scanner.
For example if you want to chose field C3, you have to type into the scanner C3.
At the moment im struggleing a little bit with the field.
I had 2 ideas but both didn't work out very well.
in the first try i tried to create everything with 2 for loops and 1 array but my problem was that I couldn't add 2 charrs, so I had the chars 0 to 9 and the charrs A to J.
In the second try I created 3 array, one with the numbers 0 to 9 and anothe array A to J and in the third array i wanted to combine both arrays. And now I'm wondering if this it's possible if I can acctually combine them in the way I want and if it's possible could somebody give me some help?
import java.util.Scanner;
import java.util.Arrays;
public class Minesweeper {
public static void main (String[] args) {
char c = 'A';
char d = '0';
char e = '9';
char f = 'J';
char[][] feldz = new char[11][11];
char[][] feldb = new char[11][11];
char[][] feld = new char[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldz[i][j] = ' ';
System.out.print(feldz[i][j] + " |");
}
if (d > e) {
d = '0';
}
if (d <= e && i > 0){
feldz[i][j] = d;
System.out.print(feldz[i][j] + " |");
}
if (i > 0 && j == 10) {
d++;
}
}
System.out.println("");
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (i > 0 && j == 0){
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (c > f) {
c = 'A';
}
if(c <= f && j > 0){
feldb[i][j] = c;
System.out.print(feldb[i][j] + " |");
c++;
}
if (j == 10){
System.out.println("");
}
}
}
}
}
You don't actually need array to print the maze , nested loops is enough for that. 2d Array is only required to store the input. Please try the below code:
int size = 10;
int [][] maze = new int[size][size];
while (true){
System.out.print(' ');
for (int i = 0; i < size; i++) {
System.out.print('|');
System.out.print((char) ('A' + i));
}
for (int i = 0; i < size; i++) {
System.out.println("");
System.out.print(i);
for (int j = 0; j < size; j++) {
System.out.print('|');
if(maze[i][j] > 0) {
System.out.print(maze[i][j]);
} else {
System.out.print(' ');
}
}
}
int row = -1;
int col = -1;
System.out.println("\nEnter CoOrdinates");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length() == 2) {
char charAt = input.charAt(0);
if(charAt >= 'A' && charAt <= 'A'+size-1) {
col = charAt-'A';
}
charAt = input.charAt(1);
if(charAt >= '0' && charAt <= '0'+size-1) {
row = charAt-'0';
}
if(row != -1 && col != -1) {
System.out.println("Enter Action");
input = scanner.nextLine();
int action = Integer.parseInt(input);
maze[row][col] = action;
} else {
System.out.println("Incorrect Input");
}
}
}
I am to write a program that prints ONLY the NON-BOUNDARY AND CORNER elements of an (n*n) array, for my assignment, and this is the main part of the code:
The output I am getting is this:
As you can see, the non-boundary elements (6,7,10,11) are not in their correct positions, which I believe, is because of incorrect printing of tab spaces within the loop. (My code is totally a mess) I would like some help or suggestions to fix this. Thanks!
I generally find that flattening things (the if-conditions in particular), and putting conditions into boolean-returning methods helps. Try something like
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++ {
if (isCorner(i,j,n) || !isEdge(i,j,n)) {
//...
} else {
//...
}
}
System.out.println();
}
where isCorner(i,j,n) and isEdge(i,j,n) are defined something like
public boolean isCorner(int row, int column, int gridSize) {
//...
}
A you got a solution, just missing spaces, I'll add some smart things:
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
boolean visible = (i % (n - 1) == 0) == (j % (n - 1) == 0);
if (visible) {
System.out.printf(" %4d", a[i][j]);
} else {
System.out.print(" ");
}
}
System.out.println();
}
No longer any problems with tabs "\t", though I used spaces here.
Keep it simple, too many cases just cause problems - as you experienced.
The trick here is to consider whether to print or not. Hence I started with
a variable visible.
The border condition
i == 0 || i == n - 1
could also be written with modulo as
i % (n - 1) == 0
If this is "too smart", hard to grasp reading:
boolean iOnBorder = i % (n - 1) == 0;
boolean jOnBorder = j % (n - 1) == 0;
boolean visible = iOnBorder == jOnBorder;
The "X" pattern checks the _equivalence of i-on-border and j-on-border.
For the rest: formatted printf allows padding of a number.
Try this i have optimized your if condition
No need to again check for i == 0 or i == n-1
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==0 || i==n-1){
if(j==0 || j==n-1){
System.out.print(a[i][j]);
}
}else{
if(j != 0 && j!= n-1){
System.out.print(a[i][j]);
}
}
System.out.print("\t");
}
System.out.println();
}
Just gave a try in case you might find it helpful.
public static void main(String[] args) throws ParseException {
int[][] ar = new int[4][4];
int[] input = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int pointer=0;
int imin=0,jmin=0,imax=3,jmax=3;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
ar[i][j]=input[pointer];
pointer++;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(!((i==imax && j==jmin)||(i==imin && j==jmax)||i==j) && //For skipping the corners
(i == imin || j == jmin || i == imax || j == jmax)){// Not to print the borders
continue;
}
else {
System.out.println(ar[i][j]);
}
}
}
}
I'm wondering if you could help me out. I'm trying to write a nested for loop in java that displays a number pyramid triangle that looks like
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
This is what I have so far:
class Triagle {
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
printTriagle(12);//I want to set the triangle to be height of 12
}
}
My result is not equal to the expected output:
___________*#
__________*_*#
_________*_*_*#
________*_*_*_*#
_______*_*_*_*_*#
______*_*_*_*_*_*#
_____*_*_*_*_*_*_*#
____*_*_*_*_*_*_*_*#
___*_*_*_*_*_*_*_*_*#
__*_*_*_*_*_*_*_*_*_*#
_*_*_*_*_*_*_*_*_*_*_*#
*_*_*_*_*_*_*_*_*_*_*_*#
I have updated your code and added comments so that you can understand. Refer to the code below:
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print("_");
}
String s = "_";
if (i + 1 >= n) // check if it is the last line
s = "*"; // change to print * instead of _
for (int j = 0; j <= i; j++) {
// printing stars
if (j == i)
System.out.print("*#"); // check if the last print of the line
else if (j == 0)
System.out.print("*" + s); // check if the first print of the line
else
System.out.print(s + s);
}
System.out.println();
}
}
Result:
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
Try this
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
if(i == (n-1)){
System.out.print("**");
}
else{
System.out.print((j == 0 || j == i) ? "* " : " ");
}
}
System.out.println();
}
}
Your issue is here:
for (int j=0; j<=i; j++){
// printing stars
System.out.print("* ");
}
Here, it prints a star for each number between 0 and i, but it only should print a star if it is exactly 0 or i.
Try something like this:
for (int j=0; j<=i; j++){
if ( i == n ) {
System.out.print("* ");
} else {
System.out.print(j == 0 || j == i ? "* " : " ");
}
}
EDIT: You may still have to adapt your code to get the bottom line printed correctly, in case that line has to be all stars
This is what you need to do:
public static void printTriagle(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < 2*n; j++) {
if(i == n-1) {
System.out.print((j != 2*n-1) ? "*" : "#");
}
else {
if(i+j == n-1) {
if(i == 0) {
System.out.print("*#");
break;
}
else {
System.out.print("*");
}
}
else if(j-i == n-1) {
System.out.print("*#"); break;
}
else {
System.out.print("_");
}
}
}
System.out.println();
}
I've looked over lots of posts already and they have helped a lot, but none have covered my issue. I'm trying to print out an alternating checkerboard pattern for a class assignment. My output starting on the first line and every odd line has an extra print at the end. It should be repeating a 8x8 pattern basically. Here is my code and a screenshot of my output.
I need to know how to alter the code so that I only get 8 asterisks in the odd lines instead of the 9 that are showing now.
public class Checkerboard {
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}
output
This works for me. I changed the last else statement to an else if with the condition j != length || i % 2 != 0 so now if it is an odd number row it will not print out an extra '*' at the end.
public class mainTest {
public static void main(String[] args) {
int length = 15;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else if (j != length || i % 2 != 0)
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}
Although below snippet is not optimized, but it should work for you. There is scope of simplification. Try that.
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++) {
char first = ' ';
char second= '*';
if (i % 2 == 0) {
first = '*';
second = ' ';
}
for (int j = 0; j < length; j++) {
if (j % 2 == 0) {
System.out.print(first);
} else {
System.out.print(second);
}
}
System.out.println("");
}
}
I'm writing a code to read a string and count sets of repeating
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
If I try the input
aabbcdaaaabb
I should have 4 sets of repeat decimals
aa | bb | aaaa | bb
and I know I'm not reading the first set aa because my index starts at 1. I tried fixing it around to read zero but then I tr to fix the entire loop to work with the change and I failed, is there any advice as to how to change my index or loop?
Try this code:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
Edit - counted aaaa as 4, fixed to count as 1
from what I understood from your question, you want to count number of repeating sets, then this should help.
for (int i = 0; i < word.length()-1; i++){
if (word.charAt(i) == word.charAt(i + 1)){ // found a repetition
if (i==0 || word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
Try this----
public int countRepeatedCharacters()
{
int c = 0,x=0;
boolean charMatched=false;
for (int i = 0; i < word.length(); i++)
{
if(i==word.length()-1)
{
if (word.charAt(i-1) == word.charAt(i))
c++;
break;
}
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
charMatched=true;
continue;
}
if(charMatched==true)
c++;
charMatched=false;
}
return c;
}
Try this method. It counts the sets of repeating charactors.
public static void main(String[] args) {
String word = "aabbcdaaaabbc";
int c = 0;
for (int i = 0; i < word.length()-1; i++) {
// found a repetition
if (word.charAt(i) == word.charAt(i + 1)) {
int k = 0;
while((i + k + 1) < word.length()) {
if(word.charAt(i+k) == word.charAt(i + k + 1)) {
k++;
continue;
}
else {
break;
}
}
c++;
i+=k-1;
}
}
System.out.println(c);
}
You can try something like this:-
public static void main(String str[]) {
String word = "aabbcdaaaabbc";
int c = 1;
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
c++;
} else {
System.out.println(word.charAt(i)+ " = " +c);
c = 1;
}
}
System.out.println(word.charAt(word.length()-1)+ " = " +c);
}
You can modify this as per your needs, by removing the sysouts and other stuffs.
Using length() -1 is causing you to not consider the last character in your calculations.
This is causing you to lose the last repetitive character.
Finally, I would have done this as follows:
public static int countRepeatedCharacters(String word)
{
boolean withinRepeating = false;
int c = 0;
for (int i = 1; i < word.length(); i++)
{
if (!withinRepeating && (withinRepeating = word.charAt(i) == word.charAt(i - 1)))
c++;
else
withinRepeating = word.charAt(i) == word.charAt(i - 1);
}
return c;
}