2015-10-27 50 views
-6
  1. 創建一個字符串變量並將您的全名分配給變量。
  2. 使用字符串的子字符串方法在三條單獨的行上打印出您的名字,中間名和姓氏。
  3. 修改您的程序,以便它創建一個「掃描儀」對象,以允許用戶鍵入任何三個名稱並將其存儲在字符串變量中。
  4. 修改你的程序,使它不管用戶輸入什麼三個名字(提示:使用字符串的indexof方法),都會在不同的行上打印出三個名字。

所以對於這個問題,我正在用Java來做。這是我到目前爲止。謝謝!我有這個字符串解析器的麻煩,我該如何處理它?

package stringparser; 

import java.util.Scanner; 

public class StringParser 
{  
    public static void main(String[] args) 
    {  
     String Name = "Billy Bob Joe"; 
     String first = Name.substring(0,5); 
     String middle = Name.substring(6,12); 
     String last = Name.substring(13,16); 

     System.out.println("First name: " + first); 
     System.out.println("Middle name: " + middle); 
     System.out.println("Last name: " + last); 

     Scanner in = new Scanner(System.in); 
     System.out.print("Type any 3 names: "); 

     System.out.print("First name: "); 
     String a = in.nextLine(); 

     System.out.print("Second name: "); 
     String b = in.nextLine(); 

     System.out.print("Third name: "); 
     String c = in.next(); 
    } 
} 
+4

聞起來像作業... – SJB

+1

什麼問題? – MadProgrammer

+4

*「(提示:使用字符串的'indexOf'方法)。」* < - 看起來很明顯對我來說 – MadProgrammer

回答

0

2種方式我解釋這個問題。

  1. 使用掃描儀3倍
  2. 使用的indexOf找到一個控制檯輸入最近的空格字符。

總之,我覺得很痛苦低效使用String.indexOf

最快的方法,但不一定是最好的方式。

public StringParser() { 
    Scanner in = new Scanner(System.in); 
    String name = in.nextLine(); 
    System.out.println(name.replace(" ", "\n")); // replacing all spaces with new line characters 
} 
+0

如果我走3個掃描儀的路線,我需要2班嗎? @John Giotta –

+0

不,不是你提供的給定例子。是否需要使用'indexOf'? –

+0

那麼,我只需要得到相同的輸出。當我的老師執行這個程序時,他會改變這些字符串的代碼,試圖「破壞」它。如果他不能打破它,我就贏了。我只需要執行所要求的步驟。掃描儀是否容易做3次? –

0

該程序將字符串拆分爲空格,並將其全部打印爲結果。您可以根據需要編輯for循環條件。希望它可以幫助:)

public static void main(String[] args) 
{ 
    Scanner in = new Scanner(System.in); 
    String str = in.nextLine(); 
    String[] names = str.split(" "); 
    for(int i = 0; i < names.length; i++) 
    { 
     System.out.println(names[i]); 
    } 
}