2015-01-21 56 views
2

我在競爭對手的編碼網站上執行此練習問題。我們有一個場景,我們有一個智能瀏覽器,我們不需要輸入「www」。也不是元音。瀏覽器自己輸入這兩個東西。Java程序顯示的結果比預期結果少1

我在寫一個程序,它顯示智能網址和完整的網址中字符數的比率。即。例如,www.google.com的智能網址將是ggl.com。因此程序的顯示將是7/14。我做到了,但我的顯示器是6/14。即少一個。它適用於每個測試用例。我不;知道問題出在哪裏

Scanner sc = new Scanner(System.in); 
    int t = sc.nextInt();// no of testcases! 

    while(t > 0) 
    { 
     String st = sc.next(); 
     int count = st.length(); 
     count = count-4; 
     int count1 = st.length(); 
     for(char da:st.toCharArray()) 
     { 
      switch(da) 
      { 
       case 'a': 
        count = count -1; 
        break; 

        case 'e': 
        count = count -1; 
        break; 

        case 'i': 
        count = count-1; 
        break; 

        case 'o': 
        count = count -1;//System.out.println(da); 
        break; 

        case 'u': 
        count = count -1; 
        break; 
      } 
     } 

     System.out.print((count) +"/" +count1) ; 
     System.out.println(); 
     t--; 

    } 
+1

然後將'count'設置爲'count-3'。 – Maroun 2015-01-21 08:59:14

+0

@MarounMaroun這可以適用於'.com'網址,但不適用於'.edu'網址。 – Eran 2015-01-21 09:08:30

+0

如果'count'的減量是你在元音情況下要做的唯一的事情,你可以把多個case語句放在另一個之後。因此,將刪除您的病例報告中的複製粘貼代碼。 – KnutKnutsen 2015-01-21 09:08:58

回答

10

ggl.com仍含有元音,因此你的循環會遞減counto,和你的程序將返回6而不是7.

注意,在一般,url的域名可以有不同數量的元音 - 例如,com,govnet有1,edu有2,fr有0個。你的代碼應該忽略最後一個.之後的元音。

這可以解決你的問題:

.... 
    String st = sc.next(); 
    int count = st.length(); 
    count = count-4; 
    int count1 = st.length(); 
    st = st.substring(0,st.lastIndexOf('.')); // get rid of the domain name 
    for(char da:st.toCharArray()) 
     ... 

這是假設只有在最後一次.元音應保持在計數。例如,如果您想在.co.il域中保留oi的數量,則必須更改邏輯。

+0

Got it!這樣一個愚蠢的錯誤,我完全忽略了這一部分。謝謝 ! – 2015-01-21 09:01:51