1
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Queue que = new Queue(50);

    System.out.println("Noki's Calculator");
    System.out.println("Choose an operation (*, /, +, -)");
    String inputOp = input.nextLine();
    System.out.println(" ");

    System.out.println("Now please enter your numbers. When finished, simply press enter.");
    boolean cont = true;
    while(true){
        System.out.print(" ::  ");
        String j = input.next();
        if(j != null) {
            int numb = Integer.parseInt(j);
            que.insert(numb);
        } else if (j==null) {
            input.close();
            break;
        }
    }

    que.view(); // PROBLEM: never executes this line

}

My code won't break out of the while loop, instead still asks for user input. When I press enter, it doesn't print "::" again, but never executes que.view()

3
  • 3
    then debug the code. j can never be null. When you just press enter, j is "". Commented Aug 28, 2018 at 19:30
  • 3
    Check your assumptions. Fire up your debugger when the code fails to meet your expectations. Commented Aug 28, 2018 at 19:34
  • 1
    Please do not edit your question to an extent that invalidates all already given answers. Instead, post a new question. Commented Aug 28, 2018 at 20:28

3 Answers 3

2

Use nextLine() instead of next() like below,

String j = input.nextLine();
Sign up to request clarification or add additional context in comments.

Comments

1

According to your implementation 'j' will never be null. When you hit enter "" will be assigned to j. You may need to change your logic as follows; Use input.nextLine() instead of input.next()

if(!(j.isEmpty())) {
    int numb = Integer.parseInt(j);
    que.insert(numb);
} else {
    input.close();
    break;
}

4 Comments

"j' will never be null" so why check if it is null, then?
I updated my code; the problem still persists. Is there something I can't catch?
@Ben Use input.nextLine() instead of input.next()
@ShehanCharuka Note that you can use j.isEmpty() instead of checking against "" and the length.
0

input.next() does not return "null" when you just press "enter".

change

else if (j==null)

to

else if (j.equals(""))

Edit: this doesn't exactly answer the question but it has already been answered so i am leaving it as is.

4 Comments

You are right about input.next() never returning null. However, please pay attention that while having if(j != null) the else if will never be executed. Please, consider updating your answer.
I updated my code; the problem still persists. Is there something I can't catch?
@cs.spathis Note that there is also String#isEmpty. May be more readable.
@Poger You are right i should have read the question more carefully

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.