【发布时间】:2016-06-21 14:26:23
【问题描述】:
我需要这样做: 创建一个程序,询问用户的姓名并说出该姓名包含多少个字符。 您的程序应该被结构化,以便您将名称长度的计算放在它自己的方法中:public static int calculateCharacters(String text)。测试将同时测试方法 calculateCharacters 和整个程序。
我知道如何计算字符串中的字符数。当我必须使用单独的方法时,我无法弄清楚如何做到这一点。有人可以帮我吗?
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 name = reader.nextLine ();
int cal = calculateCharacters(name);
System.out.println(Number of characters: " + cal);
}
public static int calculateCharacters(String text) {
int cal = text.length ();
//System.out.println("Number of characters: " + count ());
return cal;`
【问题讨论】:
-
你在做什么有什么问题?
-
我看不到问题。
-
@Kim,我只看到一个问题,那就是您没有在
System.out.println("Number of characters: " + cal) 上加上起始引号; -
哇哦。是的,就是这样。哈哈,太傻了。我为此工作了很长时间。我再也没有看到它。而且不知道还能尝试什么。 Thxxxxxx :)
-
我不敢相信 String.length 的意思。也许非空白字符或不同的非空白字符要计算在内。
标签: java string string-length