【问题标题】:How to match 'Scanner' with 'LenthOfString' to work together?如何将 'Scanner' 与 'LenthOfString' 匹配以协同工作?
【发布时间】:2014-07-09 13:04:50
【问题描述】:

我是 java 的初学者,但我对非常基本的功能有问题,我不太了解它们,而且我只是一年级的计算机学生。我有一个大项目要做,所以请帮我重新安排我到目前为止的代码。我正在尝试使代码计算输入到扫描仪框中的文本的字符串长度。但是我玩过代码,我真的不知道如何更改代码的布局以匹配扫描仪和 lengthOfString 并且不弄乱代码。我知道我的问题对你来说很容易,所以请帮助我,到目前为止我的代码在下面:

import java.util.*; 

public class LengthOfString {

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

        System.out.println(lengthOfString("I need your help programmers, please"));
    }

    private static int lengthOfString(String string) {
        int length = -1;

        while (true) {
            try {
            string.charAt(++length);
            } catch (StringIndexOutOfBoundsException exception) {
                break;
            }
        }

        return length;
    }

}

感谢您的帮助!

【问题讨论】:

    标签: java string java.util.scanner


    【解决方案1】:

    Strings 有一个 length() 方法。

    关于...的东西呢?

    // prompt
    System.out.println("Type your text...");
    // scanner initialization
    Scanner sc = new Scanner(System.in); 
    // getting next line by user, then getting the length and printing it
    System.out.println(sc.nextLine().length());
    // once we're done with the Scanner...
    sc.close();
    

    输出

    Type your text...
    foo
    3
    

    【讨论】:

    • 非常感谢您的代码建议,我将它们添加到我的代码中并使用它们,我还对 'length()' 方法进行了更多研究。出现了一个我无法解决的错误,但我将为此创建一个不同的问题,再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2012-09-21
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多