如何递归地执行相同的操作并仍然使用扫描仪和集合?
这是我使用集合和扫描仪参数创建的代码。我一直很困惑将它结合到递归中,我使用了迭代。
public class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter your words (type R to reverse):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("r")) {
break;
}
deque.add(line);
}
System.out.println("\n===== Reversed Lines =====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
Here's the code I have created using the collection and the scanner parameters. I've been so confused to combine it into recursive, I used iteration.
public class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter your words (type R to reverse):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("r")) {
break;
}
deque.add(line);
}
System.out.println("\n===== Reversed Lines =====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,快速回顾一下递归。
每个递归方法都由两部分组成:
您可以将负责读取用户输入的代码提取到单独的方法中,并用递归调用替换
while
循环。基本情况由两种情况表示:
sc.hasNext()
产生false
并且用户输入等于"r"< /代码>。否则,该行将被添加到队列中,并进行新的递归调用。
从队列中打印内容也可以递归地完成。此方法的基本情况是当
reverse.hasNext()
返回false
时。在递归情况中,将打印下一个元素,并进行后续的递归调用。因此,为了能够使用
Scanner
和Queue
,您可以将它们作为参数传递或使它们全局可访问。由于此任务的要求,
Scanner
和Queue
在方法readAndPrint()
内部本地声明,并作为方法的参数读取输入()。
输出
First of all, quick recap on recursion.
Every recursive method consists of two parts:
You can extract the code responsible for reading the user input into a separate method and substitute the
while
loop with the recursive call.The base case is represented by two situations:
sc.hasNext()
yieldsfalse
and user input is equal to"r"
. Otherwise, the line will be added to queue and a new recursive call will be made.And printing the content from the queue could be done recursively as well. The base case for this method is when
reverse.hasNext()
returnsfalse
. In the recursive case the next element will be printed, and a subsequent recursive call will be made.So in order to be able to use
Scanner
andQueue
you can either pass them as parameters or make them accessible globally.Because of the requirements for this task,
Scanner
andQueue
are declared locally inside the methodreadAndPrint()
and as parameters of the methodreadInput()
.Output