-1
import java.util.Scanner;
 public class Test{
  public static int countUppercase(String s){
  int count = 0;
 for(int i = 0; i<s.length(); i++){
 if(s.charAt(i)>='A'&&s.charAt(i)<='Z'){
 count++;
}
} 

 return count;
 }
 public static void main(String[] args){
System.out.println("Please enter a word to check for uppercase:");
  Scanner input = new Scanner(System.in);

  String s=input.nextLine();
  countUppercase(s);
   }
 }

Why doesn't this code work ? It just takes the input but does not return the count !

Ralph
  • 2,959
  • 9
  • 26
  • 49
  • I'm assuming your goal is to print the result? If that's the case, you'll want to use `System.out.println` – jpm Nov 21 '12 at 04:18
  • Then what does the return do if I print it?? – Ralph Nov 21 '12 at 04:19
  • `return` makes the result of a method available to the caller (in this case `main`). It's up to the caller what to do with the returned value. If you want to print it, main needs to say "Print the value returned by this method." Or in code: `System.out.println(countUppercase(s));` – jpm Nov 21 '12 at 04:21

4 Answers4

3
System.out.println(countUppercase(s));

Because you are not printing the output

Shamis Shukoor
  • 2,515
  • 5
  • 29
  • 33
  • Shouldn't the return print the value of count ? – Ralph Nov 21 '12 at 04:18
  • No it just returns the value to the call of the function int c = countUppercase(s); Now c will have the count. The value is returned to c. And its better to use isUpper() – Shamis Shukoor Nov 21 '12 at 04:19
1

Have you tried

if(Character.isUpperCase(s.charAt(i)))
{
     count++;
}

EDIT I just executed your code. Its works fine. Only thing is that you are not priniting the result. Is that your problem?

int nUpperCase = countUppercase(s);
System.out.println(nUpperCase );
PC.
  • 6,870
  • 5
  • 36
  • 71
  • welcome :) using `Character.isUpperCase` is a better approach according to me. (Why write some functionality if java already provides it) – PC. Nov 21 '12 at 04:26
0

Are you sure it does not return the count?

When you call the method:

countUppercase(s);

you don't use the return value.

Try this for example:

int count = countUppercase(s);
System.out.println("count is " + count);
byneri
  • 4,050
  • 5
  • 27
  • 28
0

You are not printing the output. You can also try below code:

for (int i=0; i<input.length(); i++)
{
     for(char c='A'; c<='Z'; c++)
    {
           if (input.charAt(i) == c)
          {
                    upperCaseCount++;
          }
     }
}
Bhavesh Shah
  • 3,299
  • 11
  • 49
  • 73
  • @user1804697: If any of the above answer that works for you, then please accept that answer. So that it can help others. – Bhavesh Shah Dec 04 '12 at 04:51