Hello! I am supposed to write a recursive method for my assignment in my class but I'm not sure what is wrong with the code I wrote. The method should print all of the letters of the alphabet up to (including) the parameter value.

Some examples of what it's supposed to do:

printLetters('f')
should return: abcdef

printLetters('D')
should return: ABCD

public class Homework {

public static void printLetters(char c){

	char start;
	if (c >= 'A' || c <= 'Z')
		start = 'A';
	else
		start = 'a';
	while (start <= c){
		System.out.print(start);
		start++;
	}
	
}

public static void main (String args[]){
	printLetters('f');
	System.out.println();
	printLetters('D');

}
}

Only the second one with D works. The other one print all the characters before it and goes all the way to 'A'

Any ideas???

Your method isn't recursive. A recursive method has to call itself. Although recursive method calls usually amount to loops anyway. Not going to get into that here though. Anyway...

What does the second one do? Just show us the output. My first guess would be it didn't work because you have to look at your Unicode table. If 'f' is lower than 'Z' on the Unicode table then start will be set to 'A'. You have a problem with that I'm pretty sure.

Your method isn't recursive. A recursive method has to call itself. Although recursive method calls usually amount to loops anyway. Not going to get into that here though. Anyway...

What does the second one do? Just show us the output. My first guess would be it didn't work because you have to look at your Unicode table. If 'f' is lower than 'Z' on the Unicode table then start will be set to 'A'. You have a problem with that I'm pretty sure.

Printing with D gives me:

ABCD

Printing with f gives me:

ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdef

I know it's because of the unicode thing, but how do you fix it? The one with D is how it's supposed to work. I'm not sure how to go about calling itself to make it recursive though. We just learned about these methods in class so I just wrote it how I would normally write a method to see what I could do with it. I'm not sure what to do next though.

I tried a second if statement but it gives me an error.

public static void printLetters(char c){

	char start;
	if (c >= 'A' || c <= 'Z')
		start = 'A';
	if (c >= 'a' || c <= 'z')
		start = 'a';
	while (start <= c){
		System.out.print(start);
		start++;
	}
	
}

""variable start might not have been initialized""

Edited 7 Years Ago by sselwyn: n/a

This article has been dead for over six months. Start a new discussion instead.