2013-07-12 66 views
0

我是一個開始的程序員,我必須編寫一個豬拉丁語翻譯器。我有這個代碼可以翻譯和單個單詞。我只需要知道如何通過空格將輸入分隔爲單獨的字符串。一旦我能理解這一點(我相信我正在嘗試理解數組,我不確定嗎?)我將能夠根據需要編輯代碼。非常感謝!如何分隔一個字符串:豬拉丁語翻譯器

import java.io.*; 
import java.util.*; 

public class Main 
{ 
    public static void main (String[] args) 
    { 
    Scanner scan = new Scanner(System.in); 
    String str = scan.nextLine(); 
    String a = str.substring(0,1); 
    String b = str.substring(0,2); 
    String c = str.substring(0,3); 
    String d = str.substring(0,4); 
    String answer = ""; 
    if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u")) 
    { 
     System.out.print(str + "way"); 
     } 
    else 
     { 
     answer = str.substring(2,str.length()); 
     String answer2 = str.substring(1,str.length()); 
     String answer3 = str.substring(3,str.length()); 
     String answer4 = str.substring(4,str.length()); 
     if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u"))) 
      { 
      System.out.print(answer4 + d + "ay"); 
      } 
     else if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u"))) 
      { 
      System.out.print(answer3 + c + "ay"); 
      } 
     else if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u"))) 
      { 
      System.out.print(answer + b + "ay"); 
      } 
     else if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u"))) 
     { 
     System.out.print(answer2 + a + "ay"); 
     } 
     } 
    } 
    } 

回答

0

您可以在一個或多個空格字符每次出現使用

String[] words = str.split("\\s+"); 

.split("\\s+")分裂str

我建議你重構處理一個單詞到自己的方法的代碼,並將其應用於words的每個元素。

+0

我覺得這應該可行,但是當我創建字符串單詞時應該發生什麼?此外,我打印的單詞,它給了我:[Ljava.lang.String; @ 1f86e79 – Gihadi

+0

@Gihadi'進口java.util.Arrays'和打印'Arrays.toString(單詞)'(數組不覆蓋'toString( )'方法,令人討厭,所以我們不得不訴諸使用這種實用方法)。 – arshajii

0

通過空格分隔字符串非常簡單。您已經知道如何將掃描程序包裹在System.In中 - 如果您將掃描程序包裝在字符串周圍,則其默認的標記分隔符是空格。

String test = "Hello world, my name is bob."; 
Scanner sc = new Scanner(test); 
while (sc.hasNext()) 
    System.out.println(sc.next()); 

這個代碼塊的輸出將是

Hello 
world, 
my 
name 
is 
bob. 

你可以將這個邏輯掰開你的輸入和豬latinize單個單詞。

+0

也學習arshajii的答案。這是一種更簡單的方法,無需使用新掃描儀的開銷。兩種方式來剝皮貓,他是更優雅。 –

0

可能想嘗試JavaCC,雖然它的真正用途可能更多用於複雜的解析情況。對於你想要的,做String.split方法可能更容易。

+0

arshajii給出了一個使用String.split的例子 – pinmonkeyiii