2012-07-18 25 views
0

此代碼是main函數內部:反轉字符 - 棧的實現

Scanner input = new Scanner(System.in); 

System.out.println("Type a sentence"); 
String sentence = input.next(); 

Stack<Character> stk = new Stack<Character>(); 
int i = 0; 

while (i < sentence.length()) 
{ 
    while (sentence.charAt(i) != ' ' && i < sentence.length() - 1) 
    { 
     stk.push(sentence.charAt(i)); 
     i++; 
    } 
    stk.empty(); 
    i++; 
} 

這是empty()功能:

public void empty() 
{ 
    while (this.first != null) 
     System.out.print(this.pop()); 
} 

它不能正常工作,通過鍵入example sentence我得到這個輸出:lpmaxe。第一個字母丟失,循環停止,而不是計算經過空間到句子的下一部分。

我試圖做到這一點:

This is a sentence --->sihT si a ecnetnes

+3

顛倒句子中的單詞和句子中的字符之間存在細微的差異。你想要做什麼? – 2012-07-18 15:34:10

+0

我想在句子中的每個單詞中反轉字符,同時保持相同的單詞順序。你可以說這是家庭作業 - 我只是在網上尋找問題,以提高我對堆棧和隊列的理解。 – amiregelz 2012-07-18 15:37:05

+1

你有沒有試過檢查'sentence'的值是什麼,和/或['Scanner.next()'](http://docs.oracle.com/javase/6/docs/api/java /util/Scanner.html#next())說它會做? – 2012-07-18 15:38:44

回答

3

每修改原來的職位,其中OP現在表明他的目標,是扭轉的話字母順序在一個句子中,但將這些詞留在他們的初始位置。

我認爲最簡單的方法是使用字符串split函數,迭代單詞並顛倒它們的順序。

String[] words = sentence.split(" "); // splits on the space between words 

for (int i = 0; i < words.length; i++) { 
    String word = words[i]; 
    System.out.print(reverseWord(word)); 

    if (i < words.length-1) { 
     System.out.print(" "); // space after all words but the last 
    } 
} 

當所述方法reverseWord被定義爲:

public String reverseWord(String word) { 
    for(int i = 0; i < word.length(); i++) { 
     stk.push(word.charAt(i)); 
    } 
    return stk.empty(); 
} 

又凡empty方法已被更改爲:

public String empty() { 
    String stackWord = ""; 
    while (this.first != null) 
     stackWord += this.pop(); 
    return stackWord; 
} 

原始響應

原來的問題印度語因爲OP想要完全顛倒這句話。

你有一個雙循環構造,你不需要它。

考慮這樣的邏輯:

  1. 閱讀來自所述輸入串中的每個字符,並且字符推到堆棧
  2. 當輸入字符串爲空,從堆棧彈出每個字符並打印到屏幕上。

所以:

for(int i = 0; i < sentence.length(); i++) { 
    stk.push(sentence.charAt(i)); 
} 
stk.empty(); 
+0

可能是兩個循環,一個是反轉字符,一個是反轉字。 OP希望句子的詞序相同,每個詞翻轉 – 2012-07-18 15:41:30

+0

@ Jake223 - OP改變了他的帖子。原文指出了完全相反的句子。我會編輯我的迴應。 – 2012-07-18 15:44:44

1

我假設你希望你的代碼做的是扭轉反過來的每個字,而不是整個字符串。所以,給定輸入example sentence你想要它輸出elpmaxe ecnetnes而不是ecnetnes elpmaxe

你看到lpmaxe代替elpmaxe的原因是因爲你有i < sentence.length() - 1而不是i < sentence.length()你內心while -loop不處理字符串的最後一個字符。您只看到一個單詞的原因是因爲您的變量只包含輸入的第一個標記。這就是Scanner.next()所做的方法;它讀取下一個(默認)空格分隔的標記。

如果你想輸入一個完整的句子,包System.in如下:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 

,並呼籲reader.readLine()

希望這會有所幫助。

0

假設你已經得到了你的輸入sentence和Stack對象被稱爲stk,這裏是一個想法:

char[] tokens = sentence.toCharArray(); 
for (char c : tokens) { 
    if (c == ' ') { 
     stk.empty(); 
     System.out.print(c); 
    } else { 
     stk.add(c); 
    } 
} 

因此,它會通過在一個時間一個字符進行掃描。如果我們擊中了一個空格字符,我們將假設我們已經擊中了一個單詞的結尾,反過來吐出該單詞,打印該空格字符,然後繼續。否則,我們將字符添加到堆棧並繼續構建當前單詞。 (如果你想也允許輸入標點符號,如句號,逗號等,改變if (c == ' ') {爲類似if (c == ' ' || c == '.' || c == ',') {等。)

至於爲什麼你只得到一個字,darrenp已經指出了這一點。 (就個人而言,我會使用一個掃描儀,而不是一個BufferedReader,除非速度是一個問題,不過這只是我的看法。)

0
import java.util.StringTokenizer; 
public class stringWork { 
public static void main(String[] args) { 
    String s1 = "Hello World"; 
    s1 = reverseSentence(s1); 
    System.out.println(s1); 
    s1 = reverseWord(s1); 
    System.out.println(s1); 
} 
private static String reverseSentence(String s1){ 
    String s2 = ""; 
    for(int i=s1.length()-1;i>=0;i--){ 
     s2 += s1.charAt(i); 
    } 
    return s2; 
} 
private static String reverseWord(String s1){ 
    String s2 = ""; 
    StringTokenizer st = new StringTokenizer(s1); 
    while (st.hasMoreTokens()) { 
     s2 += reverseSentence(st.nextToken()); 
     s2 += " "; 
    } 
    return s2; 
} 

}

+0

考慮在你的回答中添加描述 – 2012-12-25 00:27:40

+0

不要只編碼,嘗試對你的答案說一些或解釋它。 – 2012-12-25 00:27:41

0

公共類ReverseofeachWordinaSentance {

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    String source = "Welcome to the word reversing program"; 

    for (String str : source.split(" ")) { 
     System.out.print(new StringBuilder(str).reverse().toString()); 
     System.out.print(" "); 
    } 
System.out.println(""); 

    System.out.println("------------------------------------ "); 
    String original = "Welcome to the word reversing program"; 
    wordReverse(original); 
    System.out.println("Orginal Sentence :::: "+original); 
    System.out.println("Reverse Sentence :::: "+wordReverse(original)); 
} 

public static String wordReverse(String original){ 

    StringTokenizer string = new StringTokenizer(original); 

    Stack<Character> charStack = new Stack<Character>(); 

    while (string.hasMoreTokens()){ 

    String temp = string.nextToken(); 

    for (int i = 0; i < temp.length(); i ++){ 

    charStack.push(temp.charAt(i)); 
} 
    charStack.push(' '); 
} 

    StringBuilder result = new StringBuilder(); 
    while(!charStack.empty()){ 
    result.append(charStack.pop()); 
} 

    return result.toString(); 
} 

}

0
public class reverseStr { 
public static void main(String[] args) { 
    String testsa[] = { "", " ", "  ", "a ", " a", " aa bd cs " }; 
    for (String tests : testsa) { 
     System.out.println(tests + "|" + reverseWords2(tests) + "|"); 
    } 
} 

public static String reverseWords2(String s) { 
    String[] sa; 
    String out = ""; 
    sa = s.split(" "); 
    for (int i = 0; i < sa.length; i++) { 
     String word = sa[sa.length - 1 - i]; 
     // exclude "" in splited array 
     if (!word.equals("")) { 
      //add space between two words 
      out += word + " "; 
     } 
    } 
    //exclude the last space and return when string is void 
    int n = out.length(); 
    if (n > 0) { 
     return out.substring(0, out.length() - 1); 
    } else { 
     return ""; 
    } 
} 

}

這可以通過代碼

+0

您可以在答案中添加更多解釋嗎? – DeadChex 2014-04-18 15:46:44