2017-02-19 25 views
-3

我試圖獲得空間作爲輸入字符串在Java中,但我面臨的問題。我的代碼是如何獲得空間作爲輸入在Java中的字符串和使用它作爲空

輸入應該像

情況下,一個

Ram Raja Gopal 

輸出應該是

Gopal Ram Raja 

情況下,兩個

輸入

Ram Gopal (Ram is first name and Gopal is Last name) 

輸出應該是

Gopal Ram 

import java.util.Scanner;  

public class abc { 

    static Scanner z = new Scanner (System.in); 
    static String f; 
    static String m; 
    static String s; 
public static void main(String args[]) 
{ 
    f= z.next(); 

    ab(); 
    bc(); 

    if(f!=null && m!=null && s!=null) 
    { 

     System.out.println(s+" "+f+" "+m); 
    } 
    else if(f!=null && m==null && s!=null) 
    { 
     System.out.println(s+" "+f); 
    }  
    else if(f!=null && m!=null && s==null) 
    { 
     System.out.println(f+" "+m); 
    }  
    else if(f!=null && m==null && s==null) 
    { 
     System.out.println(f); 
    } 
} 

public static String ab() 
{ 
    m=z.next(); 
    if(z.next().equals(" ")) 
    { 
     m=null; 
     return m; 
    } 
    else 
    { 
     m=z.next(); 
     return m; 
    } 
} 

public static String bc() 
{ 
    s=z.next(); 
    if(z.next().equals(" ")) 
    { 
     s=null; 
     return s; 
    } 
    else 
    { 
     s=z.next(); 
     return s; 
    } 

    } 
} 

回答

0

使用z.nextLine()如果你想讀整行,那麼你可以使用split方法分割你的String方法

String[] splited = string.split("\\s+"); 

然後你可以用任何你喜歡的方式打印它。

例子:

String str = "Ram Raja Gopal"; 
String[] splited = str.split("\\s+"); 

現在String數組包含splited串

splited[0] == "Ram"; 
splited[1] == "Raja"; 
splited[2] == "Gopal"; 

現在你可以在任何你想要的順序打印。

+0

如果我只輸入Ram,那麼它顯示運行時錯誤「arrayoutofindex」String name = z.nextLine(); \t \t \t \t String a [] = {null,null,null}; \t \t a =名稱。分裂( 「\\ S +」); \t \t \t \t \t \t 如果\t(A [0]!= NULL &&一個[1]!= NULL &&一個[2]!= NULL) \t \t { \t \t \t的System.out.println (a [2] +「」+ a [0] +「」+ a [1]); \t \t} \t \t \t \t否則如果(A [0]!= NULL &&一個[1] == NULL &&一個[2] == NULL) \t \t { \t \t \t的System.out.println (A [0]); \t \t \t} –

+0

@MandeepSingh如果你只輸入'Ram'那麼你並不需要拆分它。只需輸入並打印它 – Yousaf

0

我將創建的是,在第一格式取name的方法。您可以使用String.split(String)以空格分隔,先取最後一個條目,然後使用StringJoiner將其與最後一個順序前的每個名稱進行連接。像,

static String reArrange(String name) { 
    StringJoiner sj = new StringJoiner(" "); 
    String[] names = name.split("\\s+"); 
    sj.add(names[names.length - 1]); 
    for (int i = 0; i < names.length - 1; i++) { 
     sj.add(names[i]); 
    } 
    return sj.toString(); 
} 

然後你就可以與用戶的輸入(例如)

System.out.println(reArrange("Ram Raja Gopal")); 
System.out.println(reArrange("Ram Gopal")); 

輸出(如需要)稱之爲

Gopal Ram Raja 
Gopal Ram 
相關問題