0

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

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

请输入您的全名: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
4

5 回答 5

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
于 2013-03-09T16:26:29.843 回答
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 个单词时才有效。对于更长的名称,您应该编写一个反转数组的方法

于 2013-03-09T16:25:18.507 回答
0

转到这里http://docs.oracle.com/javase/6/docs/api/java/lang/String.html并阅读以了解。

于 2013-03-09T16:29:20.593 回答
0

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

于 2013-03-09T16:25:46.073 回答
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]);
    }
}
于 2018-02-24T03:13:29.413 回答