Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a static method in Java to return a string using loops

The full assignment is:

Write two public classes (named exactly), TextBox and TextBoxTester. TextBox contains the following overloaded static methods called textBoxString. This method returns a String value.

public static String textBoxString (int side)

The returned String value, when printed, displays as the outline of a square of side characters. The character you use is up to you. Don't forget that '\n' will force a newline character into the returned String. For example, let's assume I want to use * as the character for my box:

     String s =  textBoxString(3); 

     System.out.println(s);

will print

xxx  
x x  
xxx  

public static String textBoxString(int side, char bChar)

The returned String value, when printed, displays the outline of a square of side characters using bChar as the box character. For example,

     String s = textBoxString(4, '+'); 

     System.out.println(s);

will print

++++   
+  +  
+  +  
++++

So far, this is what I have:

public class TextBox {

    public static String textBoxString(int side) {
        int n = side;
        String string = "";
        for (int i = 0; i < n; i++) {
            if (i == 0 || i == n - 1) {
                string = "***";
            }
            else {
                string = "*    *";
            }
        }
        return string;

    }

    public static String textBoxString(int side, char bChar) {
        int n = side;
        char c = bChar;
        String string = "";
        for (int i = 0; i < n; i++) {
            if (i == 0 || i == n -1) {
                string = c + " " + c + " " + c + " " + c;
            }
            else {
                string = c + "      " + c;
            }
        }
        return string;
    }
}

My issue is returning the result. I don't know how to return the result that I need, that I would get from running this in a main method (for the first method):

int n = 3;
for (int i = 0; i < n; i++) {
    if (i == 0 || i == n - 1) {
        System.out.println("***");
    }
    else {
        System.out.println("*  *");
    }
}

1 Answers

You can use nested loops to achieve this.

public static String textBoxString(int n, char c) {
 String output = "";
 for(int i = 0; i < n; i++) { // constructing all rows
  output += c;
  for(int j = 1; j < n-1; j++) { // constructing a single row
     if(i == 0 || i == n - 1)
       output += " " + c; // use character to fill up each element in the row
     else
       output += " "; // use space to fill up
  }
  output += " " + c +"\n";
 }
return output;
}

Run and print

x x x x x
x       x
x       x
x       x
x x x x x
like image 141
Nikhil Avatar answered Jun 14 '26 01:06

Nikhil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!