Java dead code warning + no rectangle forming? - java

I am unsure as to why I'm getting a dead code warning for my for loops, and I also don't know why only 1 of the symbols is printed, rather than the desired rectangle.
public static String rectangle(int row, int col, char thing) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String character = "" + thing;
return character;
}
return "\n";
}
return "";
}
I tried putting the String character above the for loops, but still the same error. I cannot use any System.out.print in my code either. I tried int i = 1; i <= row, also tried it without the return ""; but I get an error for "no string returned."

The first return will terminate the method on the first iteration of the loop. Instead of all those returns, you should append to the string and only return at the end:
public static String rectangle(int row, int col, char thing) {
String result = "";
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String character = "" + thing;
result += character;
}
result += "\n";
}
return result
}
Having said that, using a StringBuilder would probably be more performant:
public static String rectangle(int row, int col, char thing) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result.append(thing);
}
result.append("\n");
}
return result.toString();
}

The lines
}
return "\n";
}
return "";
}
will not normally run because after the first inner loop executes, you are returning the new line character as a string, terminating the function at that point. The compiler spots that, and hence you get the "dead code warning". The answer above (by #Mureinik) explains how to fix that.

The problem here is that as soon as inner for loop will finish for the first time it will return an empty line and last return statement is of no use and will only execute if row is zero and second problem is that you've declared the variable inside the loop which is only accessible inside the loop so you've to declare it before the loop to return it as an answer, so replace the first return statement with string or stringBuilder or whatever you're using and declare a inside the method outside the loop.
So this is how the code would look:
public static String rectangle(int row, int col, char thing) {
StringBuilder b = new StringBuilder();// using StringBuilder instead of string as it is faster
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
b.append(""+thing);
}
b.append( "\n");
}
return b+"";//converting StringBuilder to string
}

Related

How to print int n values

I am new to Java and just start my journey but i have problem with this simple function.
I am should have result like that
*2345
**345
***45
****5
But my function return something else :D What should I have to change?
public class Main08 {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (j < n) {
System.out.println(row += "*");}
else {
System.out.print(n);}
}
}
}
}
You can try like this:
public class MyClass {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n; j++) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(j + 1);
}
}
System.out.print(" ");
}
}
}
Your issue is, that you prolonged the string multiple times and every time print it out again. I changed it such, that I only print out the numbers and asterisks depending on how the i and j relate to each other.
Also i limit the outer loop to n-1, because otherwise you will print 6 blocks (because you are starting from zero) and have a block of only asterisks at the end.
Output: *2345 **345 ***45 ****5
What you are asking is a way to replace some characters in an existing string.
The easiest way is to use the StringBuilder class because you can manage the characters, while a String is an unmodifiable sequence of characters:
A mutable sequence of characters.
In particular you need to use the method replace that:
Replaces the characters in a substring of this sequence with characters in the specified String
So to pass from an original string 12345 to **345 for example you need to do the following:
// THe original string
String original = "12345";
// THe StringBuilder populated with the original string
StringBuilder stringBuilder = new StringBuilder(original);
// Replacing the first two characters (so 12) with the string **
// to obtain the stringbuilder holding **345
stringBuilder.replace(0, 2, "**");
// Get the string **345
String result = stringBuilder.toString();
You can put this logic in your loop and apply it multiple times.
Eventually you can reuse the same StringBuilder, so in this case you need to replace a single character for each step of your for loop.
public class Main08 {
public static void main(String[] args) {
int n = 4;
int countStar=0;
int startNum=1;
for (int i = 1; i <= n; i++) {
//for displaying the "*"
countStar++;
startNum++;
for (int j = 1; j <= countStar; j++)
System.out.print("*");
//for displaying the digit
for (int k = startNum; k <= 5; k++)
System.out.print(k);
}
}
}
You can take a outer loop and inside the outer loop take two inner loops . one for printing * and the other for printing the digit. This can help you in solving other design problems if you understand the logic.
You could try this :
public static void main(String[] args) {
int n = 5;
String row = "";
for (int i = 1; i <= n; i++) {
row += i;
}
for (int i = 1; i < n; i++) {
StringBuffer buf = new StringBuffer(row);
buf.replace(0, i, "*".repeat(i));
System.out.println(buf);
}
}
The first loop create the initial row you want, and the second loop will replace the characters by stars.
The repeat appends * with same long as iterator i dynamically

Why am I getting an array out of bounds exception/no console output with cipher?

I can't see a clear reason why I'm getting an Array out of Bounds at this line:
matrix[row][col++] = plainText.charAt(i);
Could anyone elucidate me here? I get the out of bounds exception when I replace this:
cipherText = Arrays.deepToString(matrix);
with a sysout of the matrix. With the original code in place I simply get no console output.
Thanks for looking, I'm rather lost if that wasn't glaringly apparent.
import java.util.*;
public class RailFenceCypher {
public String encrypt(String plainText, int key) {
String cipherText = null;
boolean check = false;
// The 2d array to store the encrypted/decrypted text
char[][] matrix = new char[key][plainText.length()];
// Filling in the blank spaces in the array
for (int i = 0; i < key; i++) {
for (int j = 0; j < plainText.length(); j++) {
matrix[i][j] = '\n';
// Checking whether going up or down in the array, reversing if at top or bottom
int row = 0;
int col = 0;
for (int k = 0; k < plainText.length(); k++) {
if (row == 0 || row == key - 1) {
check = !check;
}
// entering the char into the row
matrix[row][col++] = plainText.charAt(i);
// finding the next row using check for direction
if (check) {
row++;
} else
row--;
}
}
for (int j = 0; j < key; j++) {
for (int m = 0; m < matrix.length; m++) {
if (matrix[j][m] != '\n') {
cipherText = Arrays.deepToString(matrix);
}
}
}
}
return cipherText;
}
}
I doubt that matrix.length() returns the length of [m], so your last for loops runs over the end of the array.
You possibly wanted to use plainText.length() instead as you did in the two for loops above.

Change a method that uses System.out.print() to work with System.out.println()

I have the following code which works perfectly fine:
public static void printTrain(String[][] train, int max_height) {
// Controls the height, 0 means the top
for (int i = 0; i < max_height; i++) {
// Controls the wagon index
for (int j = 0; j < train.length; j++) {
if (j != train.length - 1)
System.out.print(train[j][i] + " ");
else
System.out.print(train[j][i]);
}
System.out.println();
}
}
However, for my current project I am only allowed to use a special library (Terminal) which only allows me to use Terminal.printLine(...);.
So I have to change the method so that it only uses Terminal.printLine() <=> System.out.println().
This is how far I got:
public static void printTrain(String[][] train, int max_height) {
StringBuilder trainGraphic = new StringBuilder();
// Index for the height of a wagon
for (int i = 0; i < max_height; i++) {
// Wagon index
for (int j = 0; j < train.length; j++) {
if (j != train.length - 1) { // This means you need to print the connector
trainGraphic.append(train[j][i]).append(" ++ ");
} else {
trainGraphic.append(train[j][i]).append(" ");
}
}
Terminal.printLine("");
}
}
No matter what I tried, it didn't work out as expected and always prints it out wrong.
How do I change the code so it only uses Terminal.printLine()?
Currently you're creating one StringBuilder for the whole method - but never actually printing the result of it. Instead, create one StringBuilder per line of output. It's not a big change from your original code:
public static void printTrain(String[][] train, int max_height) {
// Controls the height, 0 means the top
for (int i = 0; i < max_height; i++) {
// Create a StringBuilder for this specific line
StringBuilder builder = new StringBuilder();
// Controls the wagon index
for (int j = 0; j < train.length; j++) {
if (j != train.length - 1)
builder.append(train[j][i] + " ");
else
builder.append(train[j][i]);
}
// Print out the line we've prepared in the StringBuilder
Terminal.printLine(builder.toString());
}
}

Giving the console output as return statement Java

I am new to coding and I have to code a NxN star grid as assignment. There is a tester program of the professor which gives input and tests the code.
The problem is that we have to write the code as a method and the test gets whatever I put to my return statement as the result instead of the correct output. How can I rearrange the code that the return statement will give me the result?
public class Assignment
{
public static void main(String[] args)
{
run(0);
}
public static int run(int i)
{
for (int row = 0; row < i; row++)
{
for (int col = 0; col < i; col++)
System.out.print("*");
System.out.print("\n");
}
//How can I change the return so that the tester gets the
//correct result?
return ?output?;
}
}
If I understood you well, you want to have result in some object to return it. There are many possibilities, for example:
public static String run(int size) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
sb.append("*");
}
sb.append("\n");
}
System.out.println(sb.toString());
return sb.toString();
}
You need to change a return type to String.

how to print the row numbers in a 2d array game board in java

I am working on a java Othello game and am using a 2D array with padding to build the board. I have the board printing just fine, the columns are labeled "a -h" but i need the rows to be numberd "1-8" and cannot figure out how to do this. my code is as follows:
void printBoard() {
String results = "";
OthelloOut.printComment(" a b c d e f g h");
int row = board.board.length;
int col = board.board[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}
}
the othelloOut class sort of extends the System.out print statements
public class OthelloOut {
static public void printMove(PieceColor color, Move amove){
System.out.printf("%s %s\n", color, amove);
}//printMove
static public void printComment(String str){
System.out.printf("C %s\n", str);
}//printComment
static public void printReady(PieceColor color){
System.out.printf("R %s\n", color);
}//printReady
}//OthelloOut
any help will be much appreciated. If this needs to be clarified more just let me know! thanks.
UPDATE: Numbers print but i prints 0 - 9 and i want it to skip the digits 0 and 9 to where its blank in the positions of those two numbers. Any suggestions? Thanks for the help guys!
Your best bet is doing it here:
for (int i = 0; i < row; i++) {
OthelloOut.printComment(i); // Obviously not exactly like this.
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}
Remember that you're not using println, you're using print. You want all other text to be printed onto the same line as i.
And while I'm here..
I would be using a StringBuilder, instead of concatenating a String.
for (int i = 0; i < row; i++) {
StringBuilder results = new StringBuilder();
OthelloOut.printComment(i); // Obviously not exactly like this.
for (int j = 0; j < col; j++) {
results.append(pieces[board.board[i][j] + 2]);
}
OthelloOut.printComment(results.toString());
}
You can add the row number at each row iteration like this:
for (int i = 0; i < row; i++) {
results += i + 1; // add the row number
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}

Categories

Resources