English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am trying to make a method here that will scan if the first letter of the word is a capital or not. But why doesn;t this work:

private boolean scanCapital (String s)
{
boolean result = false;
String AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String p = "";
p += s.charAt(0);
for (int i = 0; i<= AZ.length()-1; i++)
{
if (p.equals(AZ.charAt(i)))
result = true;
}
return result;
}

2006-10-30 11:21:05 · 2 answers · asked by ? 1 in Computers & Internet Programming & Design

2 answers

Here you go:

public class IsCapital{

public static void main(String[] args){

String capitalString= "I am";
String notCapitalString= "i Am Not";
System.out.println( "Is the first letter a captital?: " + scanCapital(capitalString) );
System.out.println( "Is the first letter a captital?: " + scanCapital(notCapitalString) );
}

private static boolean scanCapital (String s){
Character c = new Character( s.charAt(0) );
return Character.isUpperCase( c );
}
}

2006-10-30 14:52:37 · answer #1 · answered by Mark M 2 · 0 0

You must be using Java5. When you execute this:
p.equals(AZ.charAt(i))
you are comparing a String object (variable p) with a Character object (result of autoboxing the char returned by AZ.charAt(i) ). This will always return false since they are not of the same or compatable type. Instead, make p a char, and do a direct comparison, i.e.:
char p = s.charAt(0);
...
if (p == AZ.charAt(i))
result = true;

BTW, the Character class has a nice static method called isUpperCase, e.g.
private boolean scanCapital(String s){
boolean result = false;
if (s.length() > 0){
result = Character.isUpperCase(s.charAt(0));
}
return result;
}

Mark M tried to show this, but did it wrong (the argument is of type char, not Character).

2006-10-30 19:22:43 · answer #2 · answered by vincentgl 5 · 0 0

fedest.com, questions and answers