获取字符串方法Java的长度

时间:2016-06-21 14:26:24

标签: java string string-length

我需要这样做: 创建一个程序,询问用户的姓名并说明该名称包含的字符数。 您的程序应该是结构化的,以便您可以在其自己的方法中计算名称长度: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;`

1 个答案:

答案 0 :(得分:2)

错误是什么?我在这里没有看到逻辑上的任何错误,只有几个语法问题,比如错过引号和#34;字符数:&#34 ;,在calculateCharacters方法的末尾缺少大括号,以及reader.nextLine和()之间的额外空格。

你的方法调用看起来很好。

相关问题