How do I use a String outside the main method in this case?

Viewed 123

I want to call the String "word" that I declared in my main method

   for (int i = 0; i<n; i++){
        System.out.println("Type the required word list");

        String word = sc.nextLine();
        ncount++;
    }

and use it inside the method "countTest"

public static boolean countTest( ) {

    char beginning  = word.charAt(0);
    char end = word.charAt(word.length()-1);

    if ((beginning >= 65 && beginning <= 90) && end >= 48 && end <= 57 && word.toLowerCase().contains("ok")) 

    return true;
}

I'm unfamiliar with methods and how they work, the fact that the string is inside the for loop throws me off even more and I cant think of a way to call it.

Current Error Message:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: word cannot be resolved

3 Answers

You can pass the word variable in the argument of countTest() function.

for (int i = 0; i<n; i++){
    System.out.println("Type the required word list");

    String word = sc.nextLine();
    ncount++;

    countTest(word);
}

...
...

public static boolean countTest(word) {

    char beginning  = word.charAt(0);
    char end = word.charAt(word.length()-1);

    if ((beginning >= 65 && beginning <= 90) && end >= 48 && end <= 57 && word.toLowerCase().contains("ok")) 

    return true;
}

Simplest way is to declare word as a static field of the class, so it’s in scope of both methods:

static String word;

And delete String from the usage point so you don’t create a local variable of the same name:

word = sc.nextLine();

Then call your method, eg

if (countTest()) {
    ncount++; // count how many times returned true
}

You can declare the word into main class. Then make this word as a parameter in the countTest() method. An then call the method with parameter the word.

In the following code I use the word as no static variable. You can meke it though and use it as static as well. My scenario example:

// I don't know how your code structure is and I make my own scenario
public class YourClass {
 
    public boolean countTest(String word) {
        // you can use the word inside here, outside the main method
        char beginning  = word.charAt(0);
        char end = word.charAt(word.length()-1);
        if ((beginning >= 65 && beginning <= 90) && end >= 48 && end <= 57 && word.toLowerCase().contains("ok")) 
        return true;
    }
 
    public static void main(String[] args) {
        // This is an example of declaring the word variable
        String word = "Hello";
        // Use the following return value of the method call somewhere
        new YourClass().countTest(word); // Use the word in the countTest method outside main method
    }
}
Related