2014-03-04 40 views
0

好的,所以我正在做這個項目,要求我有一個字符串的第一個和最後一個setters出現與他們之間計算的數字和輸出。我試過重新調整一些反向字符串代碼,但我無法讓輸出顯示在我的IDE中。計數字母之間的第一個和最後 - Java

任何人都可以看看我的代碼,並提出一些建議?

public static void main(String[] args) { 
    String countWord; 
    countWord = JOptionPane.showInputDialog(null, 
      "Enter the string you wish to have formatted:"); 
} 

static String countMe(String countWord) { 
    int count = 1; 
    char first = countWord.charAt (0); 
    char last = countWord.charAt(-1); 
    StringBuilder word = new StringBuilder(); 
    for(int i = countWord.length() - 1; i >= 0; --i) 
     if (countWord.charAt(i) != first) { 
      if (countWord.charAt(i) != last) { 
       count++; 
      } 
     } 
     return countWord + first + count + last; 
    } 
} 
+0

什麼是「字符串二傳手」? – Rainbolt

+0

我想你想char last = countWord.charAt(countWord.length - 1);,爲什麼不只是使用countWord.length - 2來得到中間的字符數? –

+4

我不明白你想要做什麼,也不知道你有什麼問題。你能否澄清兩個? – Keppil

回答

2

使用charAt()只要建立它:

return "" + str.charAt(0) + (str.length() - 2) + str.charAt(str.length() - 1); 

""在前面引起下面要連接作爲字符串(而不是算術加)的數值。


略微更簡潔的選擇是:

return countWord.replaceAll("(.).*(.)", "$1" + (str.length() - 2) + "$2") 
+0

我會在哪裏實施? –

+0

刪除該方法的所有代碼,並用此單行替換它。您當然需要調用它並顯示返回的字符串。 – Bohemian

0

你可以將String.length()方法來獲得字符串的總長度。您的代碼會是這樣的:

int totalLength = countWord.length(); 
int betweenLength = totalLength - 2; // This gives the count of characters between first and last letters 
char first = countWord.charAt(0); 
char last = countWord.charAt(str.length() - 1); 
String answer = first + betweenLength + last; 
0
import javax.swing.JOptionPane; 

public class Main{ 

    public static void main(String[] args) { 
     String countWord; 
     countWord = JOptionPane.showInputDialog(null, 
       "Enter the word you wish to have formatted:"); 
     JOptionPane.showMessageDialog(null, countMe(countWord)); 
    } 

    static String countMe(String countWord) { 
     int count = 0; 
     String first = String.valueOf(countWord.charAt(0)); 
     String last = String.valueOf(countWord.charAt(countWord.length() - 1)); 
     for(int i = 1; i < countWord.length() - 1; i++) { 
      if (String.valueOf(countWord.charAt(i)) != first) { 
       count++; 
      } 
     } 
     return first + count + last; 
    } 
} 
1

一旦你確定了第一和最後一個字符,它不需要不必要的條件。剛剛嘗試這一點:

static String countMe(String countWord) { 

char first = countWord.charAt(0); 
char last = countWord.charAt(countWord.length()-1); 

int count=0; 

for (int i = 1; i < countWord.length()-1; i++) 
    { 
     count++; 
    } 
    return first + String.valueOf(count) + last; 
    } 

或者,如果不強制使用for循環,你可以把它簡單,因爲這

static String countMe(String countWord) { 
char first = countWord.charAt(0); 
char last = countWord.charAt(countWord.length()-1); 

int count = countWord.substring(1, countWord.length()-1).length(); 

return first + String.valueOf(count) + last; 
} 
相關問題