Noah Kettler
Noah Kettler

Reputation: 109

How to access user input from another method

I am trying to count the length of the name that the user inputs using an additional method. When I try to access the user input "ipnut from my method it has an error. What is wrong with my code?

import java.util.Scanner;

public class LengthOfName {
    public static void main(String[] args) {
         Scanner reader = new Scanner(System.in);
         System.out.println("Type your name: ");
         String input = reader.nextLine();


   calculateCharecters(text);

}
public static int calculateCharecters(String text){

    int texts = input.length();
    System.out.println("Number of charecters: " + texts);
    return texts;
}

}

Upvotes: 1

Views: 2789

Answers (3)

MarioK17
MarioK17

Reputation: 63

change calculateCharecters(text) should be calculateCharecters(input)
and input.length() should be text.length()

public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    System.out.println("Type your name: ");
    String input = reader.nextLine(); //"input" store the user input

    calculateCharecters(input); //and go through this metod

}

public static int calculateCharecters(String text) { // now "text" store the user input 

    int texts = text.length(); //here "texts" store the "text" lenght (text.lenght()) or number
                               //of characters

    System.out.println("Number of charecters: " + texts); //printing number of characters
    return texts; //returning number of characters so
}

you can do this in your main

int characterLength = calculateCharacters(input); //because your method return an int
System.out.println("Number of charecters: " + characterLength);

Upvotes: 0

Bruce
Bruce

Reputation: 8849

change calculateCharecters(text); as calculateCharecters(input);

import java.util.Scanner;

public class LengthOfName {
    public static void main(String[] args) {
         Scanner reader = new Scanner(System.in);
         System.out.println("Type your name: ");
         String input = reader.nextLine();


   calculateCharecters(input);

}
public static int calculateCharecters(String text){

    int texts = input.length();
    System.out.println("Number of charecters: " + texts);
    return texts;
}
}

Upvotes: 1

brso05
brso05

Reputation: 13222

calculateCharecters(text);

Should be:

calculateCharecters(input);

You need to pass your input to your method.

text is your parameter for the method you are calling. You should pass input to text.

Upvotes: 0

Related Questions