I need to do a Looping Pattern, a familiar exercise whereby you input the height and get a certain pattern. The pattern I need to generate is as follows:
AA
AABB
AABBAA
Above is the pattern for a height of 3. I can't seem to have ANY output. Any idea whats wrong? I have seen sample codes but i cant seem to figure out whats wrong with mine.
import java.util.Scanner;
public class P4 {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
int height = userInputScanner.nextInt();
int i=0, line = 0, a;
// Start setting out the lines
for (i = 1; i != height ; i++){
System.out.printf("i = " + i );
a = i;
// Printing out individual lines
for( line = i; line == 0; line-- ){
// Every ODD part print AA
if (i%2 != 0)
System.out.printf("AA");
// Every EVEN part print BB
else
System.out.printf("BB");
}
}
}
}
// Can use APPEND to string, but unable to use print
// Line = "AA" / "BB" + Str
for (line = i; line == 0; line--)
Take a look at that line. Unless line is equal to 0, this loop will never run.
The first thing is that it's not necessary to define the i and line with 0 in the beginning because java does this for you if you just type int i, line, a;
.
A more secure way for your outside loop is to keep looping if i <= height because if i goes for some reason above height it will still work and I don't think this is what you want.
And what is the a variable doing there? It's pretty useless if you never use it except to equal it with i every loop.
To print out the correct lines, I think it's a good idea to create the lines using the StringBuffer . Here is how to use it: http://www.tutorialspoint.com/java/java_string_buffer.htm
For these errors I think it's best to use a debugger and set a breakpoint on the scanner so you can see step by step what you program is doing and what its variables are.
You can do this easily with an IDE like eclipse.
You do not need second for loop. To obtain the output like:
AA
AABB
AABBAA
Have a look
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
int height = userInputScanner.nextInt();
int i=0, line = 0, a;
String str="";
// Start setting out the lines
for (i = 1; i <=height ; i++){
// Every ODD part print AA
if (i%2 != 0){
str+="AA";
System.out.printf(str+"\n");}
// Every EVEN part print BB
else{
str+="BB";
System.out.printf(str+"\n");
}
}
}
OUTPUT:
5
AA
AABB
AABBAA
AABBAABB
AABBAABBAA
The following is a java-8 solution for your problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.rangeClosed(1, i)
.mapToObj(j -> j == i ? j % 2 == 0 ? "BB\n" : "AA\n" : j % 2 == 0 ? "BB" : "AA")
.forEach(System.out::print)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.