2012-07-18 51 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