2016-08-04 64 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代码的重构等部位。

相关问题