java - 生成反向词

标签 java

我是java初学者,我正在网上做练习问题。我尝试尝试这个问题,但我不明白这个错误。

编写一个名为 processName 的方法,该方法接受控制台的扫描仪作为参数,并提示用户输入他或她的全名,然后以相反的顺序打印名称(即姓氏、名字)。您可能会认为只会给出名字和姓氏。您应该使用扫描仪立即读取整行输入,然后根据需要将其分解。以下是与用户的对话示例:

请输入您的全名:Sammy Jankis 你的名字倒序是 Jankis,Sammy

public static void processName(Scanner console) {
    System.out.print("Please enter your full name: ");

    String full=console.nextLine();

    String first=full.substring(0," ");
    String second=full.substring(" ");

    System.out.print("Your name in reverse order is: "+ second + "," + first);

}

也许我会解释我的代码。所以我尝试将这两个词分开。所以我使用子字符串来查找这两个词,然后我硬编码来反转它们。我认为逻辑是正确的,但我仍然得到这些错误。

Line 6
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol  : method substring(int,java.lang.String)
location: class java.lang.String
    String first=full.substring(0," ");
                     ^
Line 7
You are referring to an identifer (a name of a variable, class, method, etc.) that is not recognized. Perhaps you misspelled it, mis-capitalized it, or forgot to declare it?
cannot find symbol
symbol  : method substring(java.lang.String)
location: class java.lang.String
    String second=full.substring(" ");
                      ^
2 errors
33 warnings

最佳答案

public static void processName(Scanner console) {
    System.out.print("Please enter your full name: ");

    String[] name = console.nextLine().split("\\s");

    System.out.print("Your name in reverse order is: "+ name[1] + "," + name[0]);

}

当然,只有名称有 2 个单词时才有效。对于更长的名称,您应该编写一个反转数组的方法

关于java - 生成反向词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15312986/

相关文章:

java - 示例应用程序无法在虚拟设备上运行

Java在while循环中读取系统输入

java - 使用 java/Java EE 的浏览器检测

java - Webdriver 按坐标单击元素两次

java - xtext:除了Eclipse 编辑器外,如何使用语法?

java - GWT XY 绘图

java - 不重写抽象类中的抽象方法的具体子类

java - Java 中的客户端-服务器文件传输

java - 在编译时获取处理器内部方法调用(ExecutableElement)的参数类

Java 为 Integer 参数调用 String.valueOf(char[] data) 而不是 String.valueOf(int i) 并抛出 ClassCastException