0

I have a string named text and I want to count the number of its characters. But there is no method 'count' like in ObjC.

In the Internet I found the method 'length', which could be useful. But If I write:

private javax.swing.JTextField txtText;
    int counter = txtText.length();

the compiler complains: "cannot find the symbol"

I thought I need a framework to include, I am absolutely new in Java.

5
  • 5
    This should work. Can you show us the declaration of text? Commented Feb 26, 2012 at 19:08
  • Where's the rest of your code? This is probably a scope problem. Commented Feb 26, 2012 at 19:09
  • 3
    Please show the actual error message as your question is missing a lot of important details. Also, show the code above and below this line and let us know where this line of code is located. Is it in a method or constructor? I'll bet that you have this line hanging out naked in the class and not enclosed in a method, constructor, or other similar block. Or else as others have stated, your text variable is out of scope, but right now until you supply the details needed you're making us guess which isn't playing nice. Commented Feb 26, 2012 at 19:09
  • 1
    Show us the rest of your code, so that we at least know what the type of text is. And don't google for information about class methods, but read their javadoc: download.oracle.com/javase/6/docs/api Commented Feb 26, 2012 at 19:09
  • 2
    You don't have any code that gets the text from your text field. If you are, then it is probably a scope problem. If you aren't then that is probably the problem. Commented Feb 26, 2012 at 19:26

3 Answers 3

6

You must get the text from your GUI-component first:

private javax.swing.JTextField jTextField;

String text = jTextField.getText();
int counter = text.length();

JTextField itself is a GUI-Component and not a String. But getText() method gives you the text entered in this component as a String which you can then use to determine the length.

Sign up to request clarification or add additional context in comments.

Comments

0
String hello = "Hello World!";
int length = hello.length();

Seems to work for me.

Comments

0

That code should work, have you checked that everything was spelled correctly?

String text="THIS IS A TEST";
int counter = text.length();

If that still doesn't work make sure your IDE and your project are setup correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.