Answer the question
In order to leave comments, you need to log in
How to find an efficient solution to a problem (Java)?
Good day, I solved the problem, but the solution is not effective. How can you make it more efficient and shorter?
Problem Statement: Write a program that takes an integer in n as a command-line argument and uses nested loops to output a chessboard of n*n elements.
public class checkerBoard{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (i % 2 == 0){
if(j % n != 0){
if (j % 2 == 0){
System.out.print("*");
}
else System.out.print("-");
}
else{
if (j % 2 == 0){
System.out.println("*");
}
else System.out.println("-");
}
}
else{
if(j % n != 0){
if (j % 2 == 0){
System.out.print("-");
}
else System.out.print("*");
}
else{
if (j % 2 == 0){
System.out.println("-");
}
else System.out.println("*");
}
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Viktor Malkov ,
still in the piggy bank, not shorter, but will cause an attack among haters of lambdas and streams
IntStream.rangeClosed(1, n).forEach(i -> {
IntStream.rangeClosed(1, n).forEach(j ->
System.out.print((i + j) % 2 == 0 ? '*' : '-'));
System.out.println();});
IntStream.rangeClosed(1, n*n).forEach(i -> System.out.print(i % n != 0 ? (i % 2==0 ?'*':'-') : '\n'));
Java, alas, I do not know
procedure WriteCheckLine(Len: Integer; Offset: Byte);
var i: Integer;
begin
for i := Offset to Len - 1 + Offset do
begin
if i and 1 > 0 then Write('*')
else Write('-');
end;
WriteLn;
end;
procedure WriteCheckBoard(N: Integer);
var i: Integer;
begin
for i := 0 to N - 1 do WriteCheckLine(N, i and 1);
end;
procedure WriteCheckBoard(N: Integer);
var i, j, Offset: Integer;
begin
for i := 0 to N - 1 do
begin
Offset := i and 1;
for j := Offset to N - 1 + Offset do
begin
if j and 1 > 0 then Write('*')
else Write('-');
end;
WriteLn;
end;
end;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question