Как получить доступ к пользовательскому вводу из другого метода

1

Я пытаюсь подсчитать длину имени, которое пользователь вводит с использованием дополнительного метода. Когда я пытаюсь получить доступ к пользовательскому вводу "ipnut из моего метода, у него есть ошибка. Что не так с моим кодом?

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

}

Теги:
user-input

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;
}
}
  • 0
    Ах! Я знал, что это было легко. Все, что мне было нужно, это ввести пользовательский ввод в параметр.
  • 0
    так должно быть. у вас нет переменной с именем text. к.т.?
0

change calculateCharecters(text) должен быть calculateCharecters(input)
и input.length() должен быть 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
}

вы можете сделать это в своей

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

Должно быть:

calculateCharecters(input);

Вам необходимо передать свой ввод в свой метод.

текст - это ваш параметр для метода, который вы вызываете. Вы должны передать ввод текста.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню