简体   繁体   English

如何创建一个返回字符串长度的用户定义方法?

[英]How do I create a user-defined method that returns the length of a string?

I am trying to write a program that takes a user's input and outputs the number of characters they typed in. I have to do this by creating a method that calculates the amount of characters, then call that method in main to output the results. 我正在尝试编写一个程序,该程序接受用户的输入并输出他们键入的字符数。我必须通过创建一种计算字符数的方法来做到这一点,然后在main中调用该方法以输出结果。 I was encouraged to use a for loop, but I don't see how that would work. 我被鼓励使用for循环,但是我看不出它如何工作。 I can calculate the number of characters using length(), but I can't figure out how to make my method work. 我可以使用length()计算字符数,但是我不知道如何使方法起作用。 This is what I have so far: 这是我到目前为止的内容:

public static void main(String[] args) {
 Scanner scnr = new Scanner(System.in);

 String userInput = "";

 System.out.println("Enter a sentence: ");
 System.out.print("You entered: ");

 userInput = scnr.nextLine();
 System.out.println(userInput);


  return;
 }

 public static int GetNumOfCharacters(int userCount) {

  int i = 0;
  String userInput = "";
  userCount = userInput.length();


return userCount;
 }
}

My method is not returning the length of the string, it just gives me 0 or an error. 我的方法不返回字符串的长度,只是给我0或错误。

Right now, you are never calling your "GetNumOfCharacters" method in your main. 现在,您永远不会在主系统中调用“ GetNumOfCharacters”方法。 The way Java programs work, is by calling the main method and executing line per line what lies there. Java程序的工作方式是调用main方法并逐行执行其中的内容。 So you need to call you method from inside the main method. 因此,您需要从main方法内部调用方法。 On the other hand, it should get the Stirng as a parameter, so you can get its length. 另一方面,它应该将Stirng作为参数,以便获得其长度。 It would look something like this: 它看起来像这样:

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);

    String userInput = "";

    System.out.println("Enter a sentence: ");


    userInput = scnr.nextLine();
    System.out.print("You entered: ");
    System.out.println(userInput);

    int lenInput = GetNumOfCharacters(userInput);

    System.out.println("The length was: "+lenInput+" characters");
}

public static int GetNumOfCharacters(String userInput) {
    int len = userInput.length();
    return len;
}

Problems with your code: 您的代码有问题:

  • No Function call 没有函数调用

    Add function call in main() as int count=GetNumOfCharacters(userInput); main()中将函数调用添加为int count=GetNumOfCharacters(userInput);

  • Parameter datatype mismatch 参数数据类型不匹配

    change the datatype in function definition from int to String as public static int GetNumOfCharacters(String userInput) { 将函数定义中的数据类型从int更改为String ,将其更改为public static int GetNumOfCharacters(String userInput) {

  • Unwanted return statement in main() main()不需要的return语句

    remove the return from main() main()删除return

  • Not displaying the value returned from GetNumOfCharacters 不显示从GetNumOfCharacters返回的值

    Add System.out.print("Number of characters: "+ count); 添加System.out.print("Number of characters: "+ count); inside main() 内部main()

Code: 码:

   public static void main(String[] args) {
   Scanner scnr = new Scanner(System.in);

   String userInput = "";

   System.out.println("Enter a sentence: ");
   System.out.print("You entered: ");

   userInput = scnr.nextLine();
   System.out.println(userInput);

   int count=GetNumOfCharacters(userInput);
   System.out.print("Number of characters: "+ count);
   }

   public static int GetNumOfCharacters(String userInput) {
   int userCount = userInput.length();
   return userCount;
   }

OR 要么

Function is not really needed,you can remove the function and do it like this: 确实不需要功能,您可以删除该功能并执行以下操作:

public static void main(String[] args) {
 Scanner scnr = new Scanner(System.in);

 String userInput = "";

 System.out.println("Enter a sentence: ");
 System.out.print("You entered: ");

 userInput = scnr.nextLine();
 System.out.println(userInput);

 System.out.print("Number of characters: "+ userInput.length());
 }

A problem is that you are not actually calling the method 问题在于您实际上并未调用该方法

so try 所以尝试

public static void main(String[] args) {

 Scanner scnr = new Scanner(System.in);

 System.out.println("Enter a sentence: ");
 String userInput = scnr.nextLine();
 System.out.print("You entered: ");
 System.out.println(userInput);

 System.out.println ("The length is " + GetNumOfCharacters (userInput))    


 }

 // need to pass string into this method
 public static int GetNumOfCharacters(String myString) {

  int userCount = myString.length();
  return userCount;
 }
}

Your question included the line: 您的问题包括以下行:

I was encouraged to use a for loop, but I don't see how that would work. 我被鼓励使用for循环,但是我看不出它如何工作。

There's no elegant way to do this in Java because you are assumed to use String.length() to get the length of strings. 在Java中,没有完美的方法可以完成此操作,因为假定您使用String.length()来获取字符串的长度。 There is no 'end of string' marker as there is in, say, C. However you could mimic the same effect by catching the exception thrown when you access past the end of the string: 没有像C这样的“字符串结尾”标记。但是,您可以通过捕获访问字符串末尾时引发的异常来模仿相同的效果:

for (int len = 0; ; len++) {
    try {
        text.charAt(len);
    } catch (StringIndexOutOfBoundsException ex) {
        return len;
    }
}

That's not a nice, efficient or useful piece of code but it does demonstrate how to get the length of a string using a for loop. 那不是一段不错,高效或有用的代码,但是它确实演示了如何使用for循环来获取字符串的长度。

If you don't want to use predefined methods, you can do like this.. 如果您不想使用预定义的方法,则可以这样做。

 public static void main(String args[]){
 Scanner scnr = new Scanner(System.in);


 System.out.println("Enter a sentence: ");
 String userInput = scnr.nextLine();

 System.out.println("You entered: "+userInput);

char a[]=userInput.toCharArray();
 int count=0;
for(char c : a){
  count++;
}
System.out.println("length of the string is:"+count);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM