【问题标题】:A program that will let the user input a string and then output each letter on a new line一个程序,让用户输入一个字符串,然后在新行上输出每个字母
【发布时间】:2011-11-09 04:09:52
【问题描述】:
import java.util.Scanner;
public class Program3_5
{
    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);
        String input = new String();
        System.out.println("Please enter a string: ");
        input=scan.next();
        int length;
        length = input.length;
        input.substring();
        System.out.println(charAt(0));
        while (length)
            {
                System.out.println(charAt(0 + 1));
            }
        }
    }

我收到一条错误消息,指出它“找不到符号 - 可变长度” 我已经尝试了很多事情,但我无法让它工作。 Java新手!提前致谢。

例如,如果用户要输入:Hello There 输出将在单独的行上打印字母。

【问题讨论】:

  • 似乎应该将这个标记为作业。

标签: input char while-loop println


【解决方案1】:

String#length()String 的一个方法,而不是一个字段。您需要调用该方法。在 Java 中,使用括号调用(或“调用”)方法。所以,改变

length = input.length;
// to
length = input.length();

预测您看到的下一个编译错误:

while (length)

不会在 Java 中编译,因为 lengthint,但 while 的条件部分必须是布尔值。我猜你想只要字符串不为空就继续,所以将while 条件更改为

while (length > 0)

编译代码需要解决的其他问题:

此外,代码将使用String input = new String(); 进行编译,但完全不需要赋值。在 Java 中,您几乎从不需要new 一个字符串。相反,使用字符串文字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多