应该从用户读取行,直到输入标记“DONE”,此时它们反向显示。不要打印“完成”一词
这是我的代码到目前为止我不知道如何让所有这一切一起工作我知道我一直在思考这个但是任何帮助将不胜感激
import java.util.Scanner;
import java.util.Stack;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
} else {
break;
}
}
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}
答案 0 :(得分:0)
尝试像这样编写for循环:
GROUP
输入:
for (int i = word.length(); i > 0; i--) {
stack.push(word.substring(i-1, i));
}
输出:
DONE
答案 1 :(得分:0)
您始终使用最后一个字(已完成),因为您不使用al
,您只使用变量word
的最后一个内容。
您必须迭代al
尝试:
import java.util.Scanner;
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
}else {
break;
}
}
for(int j=0;j<al.size();j++){
word = al.get(j);
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}
}
如果您想以相反的顺序显示单词,而不是字符,请尝试:
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
stack.push(word);
}else {
break;
}
}
while(!stack.isEmpty()){
System.out.println("Reverse of the text \"" + stack.pop());
}
}
请记住,Stack
是LIFO(后进先出)