如何在循环中显示单词以删除每次迭代中的最后一个字母
问题声明:
创建一个在字符阵列中初始初始单词的程序(this 成为您的堆栈),并显示删除最后一个字母的单词 堆栈。
示例
输入:
LONELY
输出:
LONELY
LONEL
LONE
LON
LO
L
,这是我的代码,我只能在数组上打印字符。
但是我没有提出解决方案来继续删除最后一个字母,就像输出显示的方式一样。
并且可能需要它是合乎逻辑的。
public static void main(String[] args) {
char word[] = {'S', 'T', 'U', 'C', 'K'};
int len = word.length;
for (int x = 0; x < len; x++) {
System.out.print(word[x]);
}
}
Problem statement:
Create a program that initializes a word in a character array (this
becomes your stack) and displays the word removing the last letter on
the stack.
Example
Input:
LONELY
Output:
LONELY
LONEL
LONE
LON
LO
L
So this is my code and I have only able to print the character on the array.
But I haven't come up of a solution to keep removing the last letter, just like how the output would show.
And probably need it to be logical.
public static void main(String[] args) {
char word[] = {'S', 'T', 'U', 'C', 'K'};
int len = word.length;
for (int x = 0; x < len; x++) {
System.out.print(word[x]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将嵌套
用于
循环。内循环的变量指向特定字符。外圈中定义的变量表示需要在当前行中跳过的字符数。
语句
system.out.println()
在每个内部循环后执行,并将输出推进下一行。但是,如果您的挑战意味着您希望您创建将由字符数组支持的堆栈数据结构的实现,那将使任务更复杂。
下面的代码旨在提供有关如何进行的一般想法。
堆栈的实现中必须存在三种重要方法:
push()
- 添加了新元素(在方法主体中,我提供了指令,但遗漏了此实现,这样您就有机会获得动手体验);pop()
- 从堆栈顶部删除元素并将其返回;peek()
- 从堆栈顶部返回元素而无需删除。另外,我添加了
ISEMPTY()
和print()
方法的实现,该方法可用于检查堆栈是否为空并打印其内容,如其名称所建议。main()
-demo输出
You can use nested
for
loop.The variable of the inner loop points to a particular character. And the variable defined in the outer loop denotes the number of characters that need to be skipped in the current row.
Statement
System.out.println()
is executed after each inner loop and advances the output to the next line.But if your challenge implies that you are expected to create an implementation of the stack data structure that will be backed by the character array, that a bit more complicated task.
The code below is meant to provide the general idea on how to it.
There are three important methods that have to be present in the implementation of stack:
push()
- adds new element (in the method body I've provided the instructions but left out this implementation, so that you're given a chance to obtain a hands-on experience);pop()
- removes the element from the top of the stack and returning it;peek()
- returns the element from top of the stack without removing it.Also, I added implementations of
isEmpty()
andprint()
methods that could be used to check whether the stack is empty and to print its contents, as their names suggest.main()
- demoOutput
java
stack> stack
stack /a>说(部分)在您的情况下,我相信您需要一个
Deque&lt; partinal&gt;
。将所有值从数组中推入Deque
,然后在嵌套环中迭代Deque
。类似的东西,输出(根据要求)
The Java
Stack
Javadoc says (in part)For your case, I believe you want a
Deque<Character>
. Push all the values from the array into theDeque
and then iterate theDeque
in a nested loop. Something like,Which outputs (as requested)