2016-08-04 90 views
-1

我製作了一個程序,它將用戶輸入的字符串存儲到隊列中,然後打印出整個東西,但是我有一些問題阻止字符串「end」被打印出來打印字符串隊列時。刪除在Java中打印的最後一個字符串

public class Test { 

    protected static String testinfo; 
    Test() { 
     testinfo= "blank"; 
    } 

    public static void setTest(String newInfo){ 
     testInfo = newInfo; 
    } 

    public static String getTest(){ 
     return testInfo; 
    } 

    private static Scanner input = new Scanner(System.in); 

    public static void main(String[] args) { 
     Queue<String> queue = new LinkedList<String>(); 
     String newInfo; 

     System.out.println("Inset information for the test or quit by typing end "); 

     while (true) { 
      System.out.println("Insert information: "); 
      newInfo = input.nextLine(); 

      Test.setTest(newInfo); 

      queue.offer(Test.getTest()); 

      if (newInfo.equals("end")){ 
       break; 
      } 
     } 

     while(queue.peek() !=null) { 
      String x = queue.poll(); 
      if(x.contains("end")) { 
       queue.remove("end"); 
      } 
      System.out.println(x + " "); 
     } 
    } 
} 
+0

你爲什麼將它加入到隊列中? –

+0

您從q中刪除它,但始終將其打印出來。把'println'放在'else'中。 –

+0

while(!(queue.peek.equals((「end」))) –

回答

0

在while循環中,你已經提供了用戶輸入的字符串 - end到隊列中,您檢查中斷條件之前。事實上,字符串 - end已入隊。

重新安排在while循環應該解決這一問題的陳述你所面對

while (true) { 
     System.out.println("Insert information: "); 
     newInfo = input.nextLine(); 
     if (newInfo.equals("end")){ 
      break; 
     } 
     Test.setTest(newInfo); 
     queue.offer(Test.getTest()); 
    } 

注:我din't代碼的重構等部位。

相關問題