2013-03-09 41 views
0

我在java的初学者,我在做什么practiceit问题关闭internet.I试图尝试的问题,但我不明白的错误。生成反向话

编写一个名为processName的方法,该方法接受控制台的扫描仪作为参数,并提示用户输入其全名,然后以相反顺序(即姓氏,名字)打印名称。你可能会认为只会给出第一个和最后一个名字。你应该用扫描仪读取输入的整条生产线一次,然后根据需要打破它分开。下面是与用户的样本对话:

请输入您的全名:萨米Jankis 你按相反的顺序名字是Jankis,萨米

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); 

} 

也许我会去解释我的code.So我尝试打破这两个词apart.So我使用的串找到这两个词,然后我硬编码扭转他们。我认为逻辑是正确的,但我仍然得到这些错误。

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 
+1

子不能把字符串参数作为第二参数。 substring(int,int)是正确的。你给出的是substring(int,String,这是错误的。 – AmitG 2013-03-09 16:25:00

+0

你的意思是bth参数必须是相同的?如果它是int,那么这两个参数必须是int? – user2148463 2013-03-09 16:27:10

回答

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个字它才会起作用。对于较长的名字,你应该写这将扭转数组

+0

Hi.I还没有学会split函数。那么还有其他方法可以去做吗? – user2148463 2013-03-09 16:26:22

+0

我认为不,因为你永远不知道名字的长度,所以你不能使用子字符串,一种方法是使用indexOf()方法来定位空间位置,然后知道它的位置子字符串的名字是正确的,但是这个方法的代码会更长,而且split方法的使用非常简单,下面是一个很好的例子:http://javarevisited.blogspot.com/2011/09/string-split -example-in-java-tutorial.html – 2013-03-09 16:28:52

0

按Java API,substring()接受像substring(int beginIndex)和两个int参数,像substring(int startIndex, int endIndex)任何一个int参数,但你用字符串参数调用一个方法。所以你会得到这些错误。更多信息可以在这里 String API找到。

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 
+0

Yes.it是indexOf.I不断与子串混合在一起。非常感谢你(: – user2148463 2013-03-09 16:31:21

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]); 
    } 
} 
+0

)考虑添加一些解释 – Sunil 2018-02-24 03:48:51