0

I'm making a simple calculator, but I've run into a problem where a string input is skipped. Here is my code:

import java.util.Scanner;

public class Calculator {
    
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Calculator\n");

        while (true) {

            System.out.print("Number: ");
            float num1 = input.nextFloat();

            System.out.print("Operator: ");
            String optr = input.nextLine();

            System.out.print("Number: ");
            float num2 = input.nextFloat();


            System.out.println(num1 + num2);

        }

    }

}

I have tried doing \n but I don't know what else I should really do as I don't know what the problem is. I know input is never closed, but I have tried closing it. It has no affect and I don't want to add it right now as I am making the base system.

Kai
  • 53
  • 1
  • 6
  • Your question is not clear. What do you mean *exactly* by the phrase "string input is skipped"? – Basil Bourque Apr 24 '21 at 05:56
  • 2
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) After calling `input.nextFloat()` you should call `input.nextLine()`. Refer to the duplicate question for more details. – Abra Apr 24 '21 at 06:02

1 Answers1

0

Instead of using...

System.out.print("Operator: ");
String optr = input.nextLine();

...use this...

System.out.print("Operator: ");
String optr = input.next();

The method nextLine() is a bit finnicky. Long story short, if you use nextLine(), beware that it doesn't play well with next(), nextInt(), nextFloat(), etc.

If you want the long story, here is a more detailed explanation -- https://stackoverflow.com/a/13102066/10118965

davidalayachew
  • 304
  • 4
  • 13
  • [How should duplicate questions be handled?](https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled) You may argue that the question is not a duplicate, but I believe that it is and I also believe that many people will agree with me. I would also argue that by linking to the "duplicate" question, you are basically admitting that the question is a duplicate. I think that you should refrain from answering duplicate questions. – Abra Apr 24 '21 at 06:39
  • @Abra I disagree with the way your linked post suggests duplicate questions should be answered. If there are consequences that come from that, I accept them. But I believe the solution you have linked me to is non-constructive and causes more problems than it solves. – davidalayachew Apr 24 '21 at 06:42