生成反向词

时间:2013-03-09 16:22:04

标签: 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);

}

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

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

5 个答案:

答案 0 :(得分:1)

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个单词才有效。对于较长的名称,您应该编写一个可以反转数组的方法

答案 1 :(得分:1)

查看substring()方法的文档。它不会将字符串作为其第二个参数。

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

您可能想要的是indexOf()方法。首先找到空格字符的索引。然后找到到那时为止的子串。

  int n = full.indexOf(" ");
  String first=full.substring(o, n); //gives the first name

答案 2 :(得分:0)

根据Java API,substring()接受一个int参数,如substring(int beginIndex)和两个int参数,如substring(int startIndex, int endIndex),但您使用String参数调用。所以你得到了那些错误。更多信息可以在这里找到 String API

答案 3 :(得分:0)

答案 4 :(得分:0)

public class ex3_11_padString {
    public static void main(String[] args) {
        System.out.print("Please enter your full name: ");
        String f_l_Name = console.nextLine();
        String sss[] = f_l_Name.split(" ", 2);
        System.out.print("Your name in reverse order is " + sss[1] + ", " + sss[0]);
    }
}