haxtar
haxtar

Reputation: 2070

print out nth string using Queue

I want to print out the nth string using the Queue data type.

Ex.

$ java NthString 5
a b c d e f
< ctrl -d >

should give me:

b (the fifth string from the right)

This is what I have so far, but I do not know my next step:

public class NthString {

   public static void main(String[] args) {

      Queue<Integer> q = new Queue<Integer>();

      while(!StdIn.isEmpty()){
         q.enqueue(StdIn.readInt());
      }
   }
}

Thanks

Upvotes: 2

Views: 1163

Answers (2)

JeB
JeB

Reputation: 12133

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());
   }

}

Upvotes: 2

sgpalit
sgpalit

Reputation: 2686

First of all you should know how these stuff work, so read my comments carefully. I have written a sample for you but it is not exactly what you need but with small changes you can reach the requirement.

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++;
       }
   }
}

Upvotes: 1

Related Questions