2017-02-11 70 views
-3

這是我的代碼。它看起來如此重複。有沒有辦法讓它看起來更清潔?謝謝。我的代碼應該做這樣的事情;
輸入文本: IDK,如果我去。這是我的BFF的生日。
你輸入了:IDK,如果我去。這是我的BFF的生日。
BFF:永遠最好的朋友
IDK:我不知道java indexOf忽略第一次發生

import java.util.Scanner; 

public class TextMsgDecoder { 
    public static void main(String[] args) { 
     /* Type your code here. */ 
     String a = "BFF"; 
     String b = "IDK";  
     String c = "JK"; 
     String d = "TMI"; 
     String e = "TTYL"; 
     Scanner scr = new Scanner(System.in); 
     System.out.println("Enter text:"); 
     String f = scr.nextLine(); 
     System.out.println("You entered: "+ f); 

     if(f.indexOf(a)>=0) 
     System.out.println("BFF: best friend forever"); 
     if(f.indexOf(b)>=0) 
     System.out.println("IDK: I don't know"); 
     if(f.indexOf(c)>=0) 
     System.out.println("JK: just kidding"); 
     if(f.indexOf(d)>=0) 
     System.out.println("TMI: too much information"); 
     if(f.indexOf(e)>=0) 
     System.out.println("TTYL: talk to you later"); 



     return; 
    } 
} 
+3

將所有'indexOf(...)> ...'改爲'indexOf(...)> = ...' – janos

+0

您需要檢查'> = 0'或'> -1' – 4castle

+0

應該考慮閱讀文檔。什麼'indexOf'返回字符串中的第一個字符?如何計算字符串字符?想想爲什麼你的代碼可能會這樣做,然後仔細看看你的if語句。 –

回答

0

只是重複什麼在評論中說,(因爲評論可以被清理),

if(f.indexOf(e)>0) 

實際上應該是

if(f.indexOf(e)>=0) 

或者,甚至更好,只是使用string.contains

第三個選擇是創建一個哈希表。我不是坐在一個IDE前,我在手機上寫這一點,但這裏有一個粗略的想法(使用比「直的」 Java更接近於C#語法):

// A C# Dictionary is a hash table 
Dictionary<string, string> dict = new Dictionary<string, string>(); 
dict.Add("BFF", "Best Friend Forever"); 
// Add the rest of the abbreviations 

// Loop over every key (abbreviation) in the hash table 
foreach (string abbreviation in dict.Keys) { 
    // If the string contains the abbreviation 
    if (f.contains(abbreviation)) { 

     Console.WriteLine(abbreviation + ": " + dict[key]); 
    } 
} 

那更容易了很多如果稍後添加更多縮寫,則閱讀/更簡潔。