user3460313
user3460313

Reputation: 1

Multiple Methods

I'm trying to create my own methods to use in my main method. I have asked the user for input in my main method and have captured it using next line. However, I am unable to use it in my other methods.

static Scanner keyboard = new Scanner(System.in);

public static void main (String[] args) {       
    System.out.println("Input string of any length");
        String s = keyboard.nextLine();
        System.out.println("If you want to the program to check if palindrome, type 1."+
            " If you want the program to compute rounded sum, type 2. If you want " + 
            "the program to count unique characters, type 3");
        String o = keyboard.nextLine();
        if (o.equals("1"))
            System.out.println(isPalindrome());
}

public static boolean isPalindrome () {
    boolean palindrome = true;
    String s = keyboard.nextLine();

It is asking me to redefine string s, in my other method, even though it has already been defined in the main.

Upvotes: 0

Views: 97

Answers (2)

springcold
springcold

Reputation: 35

Adding on to Tim B's answer, it is always good to make a function full and sound.

i.e. instead of

public static boolean isPalindrome ()

Use

public static boolean isPalindrome (String text)

and pass in the text you want to check for palindrome. This makes the function more complete. Treat a function like asking someone a question. "Is this text a Palindrome?" instead of "Is Palindrome?".

Upvotes: 0

Tim B
Tim B

Reputation: 41168

This is because of variable scope. Each variable only exists in a certain part of the program and other parts can have different variables with the same name that only exist in that part.

There are plenty of tutorials around on the subject. For example:

http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

http://www.java-made-easy.com/variable-scope.html

http://www.cs.berkeley.edu/~jrs/4/lec/08

Upvotes: 3

Related Questions