1

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;
}

}

3 Answers 3

1

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;
}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! I knew it was something easy. All I needed was to put the user input into the parameter.
it should be. you don't have a variable named text. rt?
0
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.

Comments

0

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);

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.