我想使用队列数据类型。
前任。
$ java NthString 5
a b c d e f
< ctrl -d >
应该给我:
b (the fifth string from the right)
这是我到目前为止所拥有的,但我不知道我的下一步:
public class NthString {
public static void main(String[] args) {
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
}
}
谢谢
public class NthString {
public static void main(String[] args) {
Integer n = Integer.parseInt(args[0]);
Queue<Integer> q = new Queue<Integer>();
while(!StdIn.isEmpty()){
q.enqueue(StdIn.readInt());
}
while(q.size() > n){
q.dequeue();
}
StdOut.println(q.peek().toString());
}
}
首先,你应该知道这些东西是如何工作的,所以请仔细阅读我的评论。我已经为您编写了一个示例,但它并不完全是您需要的,但只需稍作更改即可达到要求。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class NthString {
public static void main(String[] args) {
// java NthString 5
// when you run this command 5 will come from args as first parameter
int nth = Integer.parseInt(args[0]);
// Since we get alfabetic from console input your queue must be type of String
Queue<String> q = new LinkedList<>();
// This is in place of your StdIn
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
try {
String s = "";
// '/' this is the exit String that is expected from user to give at last to stop reading furthermore
// in your case it is different, ctrl -d ?
while (!"/".equals((s = bufferRead.readLine()))) {
q.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
String polled = "";
int count = 1;
// now you have to poll from queue back and count to get the nth string
// since the queue is implemented as linkedlist in my case 5th element will output e instead of b
while ((polled = q.poll()) != null) {
if (count == nth) {
System.out.println(nth + " th string is " + polled);
}
count++;
}
}
}