For loop not giving the correct output
I am attempting to get all the letters A-Z to print on the screen with 10 letters per line. I created a method <private static char printChars(char ch1, char ch2, int numberPerLine> to do this and all the letters print out, only they are on the same line, and not 10 per line. Here is the code...I'm pretty sure that the problem is in the if/else statement.
Code Java:
public class Lab5_12A {
public static void main(String[] args) {
// Define variables and assign value
char character1 = 'A';
char character2 = 'Z';
int number = 10;
for (character1 = 'A'; character1 <= character2; character1++) {
System.out.printf(printChars(character1, character2, number) + " ");
}
}
private static char printChars(char ch1, char ch2, int numberPerLine) {
char result;
if (numberPerLine <= 10)
result = ch1;
else
result = ch2;
return result;
}
}
I am still really new to Java and have only been in class for about 4 weeks, so any help is appreciated!
Re: For loop not giving the correct output
Try this:
Code :
public class Lab5_12A {
public static void main(String[] args) {
// Define variables and assign value
char character1 = 'A';
char character2 = 'Z';
int number = 0;
for (character1 = 'A'; character1 <= character2; character1++) {
System.out.printf(printChars(character1, character2, ++number) + " ");
}
}
private static String printChars(char ch1, char ch2, int numberPerLine) {
String result;
if (numberPerLine % 10==0) {
result =ch1+"\n";
}
else {
if(numberPerLine==1){
System.out.printf(" ");
result =""+ch1 ;
}
result = ch1+"";
}
return result;
}
}
I hope this will be help to you