简体   繁体   English

我的do-while循环似乎没有执行我的if语句

[英]My do-while loop doesn't seem to be executing my if statement

I'm new to java, so sorry if my programming skills are poor. 我是Java的新手,如果我的编程技能很差,请抱歉。 My program needs to use a queue to simulate an I/O buffer. 我的程序需要使用队列来模拟I / O缓冲区。 It continually accepts lines of user input. 它不断接受用户输入。 If the user inserts an O(Oh) it returns the first line entered. 如果用户插入O(Oh),则返回输入的第一行。 If an X is entered it needs to end. 如果输入X,则需要结束。

This is my program: 这是我的程序:

public static void main(String[] args) {

   Queue<String> queue = new LinkedList<String>();

    Scanner input = new Scanner(System.in);
    String check = input.nextLine();

do {

  queue.add(check);

  if(check.equals("O")) {

     if(queue.peek() != null){
        String remove = queue.remove();
        System.out.println("Data: " + remove);
        }

     else if(queue.peek() == null) {
        System.out.println("Buffer empty");         
        }
  } 

 } while(!"X".equals(check)) ;

The expected input-output is: 预期的输入输出为:

line1
line2
O
Data: line1
line3
line4
O
Data: line2
O
Data: line3
line5
O
Data: line4
O
Data: line5
O
Buffer empty 
X   

My program doesn't seem to execute my if statement, as it never stops asking for input and doesn't exit once and X is given by the user. 我的程序似乎没有执行我的if语句,因为它从不停止询问输入,也不会退出并且X由用户给出。

I'm sorry if I'm missing something obvious. 如果我缺少明显的东西,我感到抱歉。

The issue is you need to read the input again at the end, after the if condition, you need to add the line: 问题是您需要在末尾再次读取输入,在if条件之后,您需要添加以下行:

check = input.nextLine();

this way you read the next inputline, otherwise check will always be the same thing which is the first thing entered. 这样,您将阅读下一个输入行,否则检查将始终与输入的第一件事相同。

First of all, 首先,

String check = input.nextLine();

is called only once whereas it should be called again at the end of the loop. 仅被调用一次,而应在循环结束时再次调用。 So it is not updated. 因此它不会更新。

Your input.nextLine() is outside of the loop so it's only called once, when adding input to your queue is called on every loop iteration, that's why it's happening. 您的input.nextLine()在循环之外,因此仅被调用一次,因此在每次循环迭代中都将输入添加到队列中时,这就是发生这种情况的原因。 Change it this way: 以这种方式更改它:

String check;
do {
  check = input.nextLine();
  queue.add(check);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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