2017-09-05 9 views
0

我試圖使用Queue並從用戶輸入中讀取一個字符串。不幸的是,它不工作。下面顯示的代碼有什麼問題?在Java中使用隊列讀取一行

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

什麼似乎是問題?你得到了什麼錯誤/結果? – nadavvadan

回答

0

@javalearner

在你的代碼,

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

您不必在此隊列(Q)添加任何價值。所以Iterator(it)每次都會返回false,while循環不會被執行。

在q上調用迭代器方法之前,您需要在隊列中添加一些值。

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

而在上面這部分中,不需要再次調用迭代器方法。您可以將it.next()的值存儲在變量中,並將其用於if塊中。

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

https://beginnersbook.com/2014/06/java-iterator-with-examples/
這將幫助您瞭解更好:)。

+0

感謝您的回答,但我嘗試使用迭代器檢查所有行的元素。你能告訴我我能做到嗎? – javalearner

0

感謝您的幫助。我解決這個問題。

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


     } 
    }