gpt4 book ai didi

java - 生成反向词

转载 作者:行者123 更新时间:2023-12-02 07:12:46 25 4
gpt4 key购买 nike

我是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com