我試圖獲得空間作爲輸入字符串在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;
}
}
}
如果我只輸入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} –
@MandeepSingh如果你只輸入'Ram'那麼你並不需要拆分它。只需輸入並打印它 – Yousaf