简体   繁体   中英

Reading a line with using queue in Java

I'm trying to use a Queue and read a string from user input. Unfortunately, it isn't working. What is the problem with the code shown below?

public static void main(String[] args) {

                // TODO Auto-generated method stub
        java.util.Queue  q=new LinkedList<String>(); 

        Scanner scan= new Scanner(System.in);
        System.out.println("Enter a data");
        String line=scan.nextLine();
        Iterator<String> it=q.iterator();
        while (it.hasNext()){
            System.out.println("dongudeyim");
            if (it.next().equals("(")){
                q.add(line);
                System.out.println(q.isEmpty());
            }
            if(q.iterator().equals(")")){
                q.poll();
            }

            System.out.println(q.isEmpty());
        }
    }

@javalearner

In your code,

  String line=scan.nextLine();
  Iterator<String> it=q.iterator();
  while (it.hasNext()){

You do not have any value added in this queue (q). So Iterator (it) will return false everytime and while loop will not get executed.

You need to add some values in queue before calling iterator method on q.

  if (it.next().equals("(")){
       q.add(line);
       System.out.println(q.isEmpty());
  }
  if(q.iterator().equals(")")){
       q.poll();
  }

And in this above part no need to call iterator method again. You can just store the value of it.next() in a variable and use that in your if block.

String value = it.next();
if(value.equals(")")) {

https://beginnersbook.com/2014/06/java-iterator-with-examples/
This will help you understand much better :).

thanks for helps . I solve it like this .

import java.util.*;


    public class Queue {

        public static void main(String[] args) {

                    // TODO Auto-generated method stub
            java.util.Queue<String>  q=new LinkedList<String>(); 

            Scanner scan= new Scanner(System.in);
            System.out.println("Enter a data");
            String line=scan.nextLine();

                System.out.println(line);

                for (int i=0;i<line.length();i++){

                    if(line.charAt(i)==('(')){
                    q.add("(");

                    } else if(line.charAt(i)==(')')){
                        q.poll();

                    }
                }System.out.println(q.isEmpty());


        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM