This site requires JavaScript, please enable it in your browser!
Greenfoot back
Zweeg
Zweeg wrote ...

2018/11/10

Strings Matching With Alphabet Question

Zweeg Zweeg

2018/11/10

#
My code is supposed to recognize if a character in a string I input is a letter or if it is a number/character. I want to remove all numbers/characters and return a string with just the original letters. When I input "h" it returns "h". When I input "3" it returns "". However, when I input "h3" it returns as "h3" instead of just "h". Could you take a look at my code and see what the problem is?
public static String lettersOnly(String plain)
	{
		String str = plain;
		String newStr = "";
		str=str.toUpperCase();
		String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		boolean realLetter = false;
		for(int a = 0; a < str.length(); a++)
		{
			for(int i = 0; i<alpha.length(); i++)
			{
				if(str.charAt(a) == alpha.charAt(i))
				{
					realLetter=true;
				}
			}
			if(realLetter==true)
			{
				newStr += str.charAt(a);
			}
		}
		return newStr;
	}
danpost danpost

2018/11/10

#
Zweeg wrote...
My code is supposed to recognize if a character in a string I input is a letter or if it is a number/character. I want to remove all numbers/characters and return a string with just the original letters. When I input "h" it returns "h". When I input "3" it returns "". However, when I input "h3" it returns as "h3" instead of just "h". Could you take a look at my code and see what the problem is? << Code Omitted >>
You will find that if you input "3h", it will return "h". In fact, if you input "1234567890h9876543210", it will return "h9876543210". It will return the input string starting at the first real letter (removing all non-real letter characters from the beginning of the string). That is because the boolean realLetter remains true once set to true inside the loop.
You need to login to post a reply.