0

I am making a program that takes a user input of two doubles and an operator, and performs a calculation. For example, if the user inputs "12 - 6", the result will be 6. It also works if the user inputs "12 6 -". I am trying to create an error check that checks if there is either not enough tokens, or too many tokens. How do I do this?

double num1, num2;
  String operator ;

  DecimalFormat decPattern = new DecimalFormat("#.00");

  System.out.println("");

  Scanner scan = new Scanner(System.in);
  System.out.print("Please enter two operands and an operator > ");

  if (scan.hasNextDouble())
  {
     num1 = scan.nextDouble();

        if (scan.hasNextDouble())
        {
           num2 = scan.nextDouble();

           operator = scan.next();

           scan.close();
        }
        else
        {
           operator = scan.next();

           num2 = scan.nextDouble();

           scan.close();
        }
  }

  else
  {
     operator = scan.next();

     num1 = scan.nextDouble();
     num2 = scan.nextDouble();

     scan.close();
  }

  System.out.println("");

  calc(operator, num1, num2);

}

Ruslan Akhundov
  • 2,178
  • 4
  • 20
  • 38

1 Answers1

0

You do not have to use Scanner, you can implement the check with leveraging Reader interface:

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
        String line = reader.readLine();
        StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.countTokens() != 3) {
            System.err.println("Wrong number of arguments");
        }
        while (tokenizer.hasMoreTokens()) {
            // Work with tokens
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

UPDATE (to satisfy instructor requirements)

Same, but with Scanner:

    try(Scanner scanner = new Scanner(System.in)) {
        String line = scanner.nextLine();
        StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.countTokens() != 3) {
            System.err.println("Wrong number of arguments");
        }
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            // Work with tokens
        }
    }
Artem Barger
  • 40,769
  • 9
  • 59
  • 81
  • Our instructor is requiring us to use the Scanner object - if I use a StringTokenizer and check the number of tokens, it either stops before anything is inputted, or keeps asking for input until the maximum is exceeded. – Will Ephlin Aug 06 '17 at 14:07
  • You can easily adopt it to use scanner if you need, see updated answer :) – Artem Barger Aug 07 '17 at 23:52