Java-使用字符串语句学习堆栈

Java-使用字符串语句学习堆栈,java,string,stack,Java,String,Stack,我必须把一个句子,不管它是什么,把每个单词放进一堆,然后倒着打印出来。所以“这是一个句子”会变成“sihT si a ecnetnes”。我用诸如“abc”之类的例子来追踪代码,但我不知道我缺少了什么来让它工作 我的问题- 无法获取要遍历堆栈的最后一个字,因为它基于空格(-1),一旦空格(-1),则给出循环出口 如何将堆栈打印出来,其中sihT显示在第一位而不是最后一位,句子的其余部分紧跟其后 输出: 短语-这是一个句子 短语长度-18 计数-0 空间-4 短语-是一个句子 短语长度-13 计数

我必须把一个句子,不管它是什么,把每个单词放进一堆,然后倒着打印出来。所以“这是一个句子”会变成“sihT si a ecnetnes”。我用诸如“abc”之类的例子来追踪代码,但我不知道我缺少了什么来让它工作

我的问题-

  • 无法获取要遍历堆栈的最后一个字,因为它基于空格(-1),一旦空格(-1),则给出循环出口

  • 如何将堆栈打印出来,其中sihT显示在第一位而不是最后一位,句子的其余部分紧跟其后

  • 输出: 短语-这是一个句子 短语长度-18 计数-0 空间-4

    短语-是一个句子 短语长度-13 计数-1 空间-2

    短语-句子 短语长度-10 计数-2 空间-1

    短语句 短语长度-8 计数-3 空间--1

    是的

    第三点 输入短语或退出(XXX):

    代码:

    公共类StackClassDriver
    {
    公共静态void main(字符串[]args)
    {
    //局部常数
    final String QUIT=“XXX”//退出的前哨值
    //局部变量
    字符串短语;//用户输入的句子
    int Count;//将计数初始化为零
    int-Space;//初始化第一个空间
    煤焦试验;
    CharStackClass Stack=新的CharStackClass();
    /**************************/
    System.out.print(“输入句子:”);
    短语=Keyboard.readString();
    //WHILE(短语不是退出值)
    while(!Phrase.equalsIgnoreCase(QUIT))
    {
    //找到第一个空格的位置
    空格=短语.indexOf(“”);
    //将计数初始化为1
    计数=0;
    //WHILE(找到一个空间)
    while(空格!=-1)
    {
    //测试输出
    System.out.print(“\n\n”);
    System.out.println(“短语-”+短语);
    System.out.println(“短语长度-”+短语长度());
    System.out.println(“计数-”+计数);
    System.out.println(“空格-”+空格);
    
    对于(int pOS=0;POS<p>)您可以简化这一点。请考虑这个伪代码

    pos = 0
    while not end of string
        if string[pos] is space
            while stack is not empty
                print stack.pop()
            end-while
            print ' '  // space between words
        end-if
        else
            stack.push(string[pos])
        end-else
        pos = pos + 1
    end-while
    // at this point, there might be another word on the stack,
    // because there was no space at the end of the sentence
    while stack is not empty
        print stack.pop()
    end-while
    

    你从哪个软件包得到键盘类?它是一个键盘工具。我看看我能不能上传它。
    pos = 0
    while not end of string
        if string[pos] is space
            while stack is not empty
                print stack.pop()
            end-while
            print ' '  // space between words
        end-if
        else
            stack.push(string[pos])
        end-else
        pos = pos + 1
    end-while
    // at this point, there might be another word on the stack,
    // because there was no space at the end of the sentence
    while stack is not empty
        print stack.pop()
    end-while