0

I'm trying to make a calculator command for my discord bot!

In this code i tried to convert the user input into a double (e.g. user inputs: *calculate 1 + 1) and send a message containing the double value! This however didn't work so then i tried converting the double back to a string!

public void onMessageReceived(MessageReceivedEvent event) {
                Message message = event.getMessage();
            String content = message.getContentRaw();
            MessageChannel channel;
            channel = event.getChannel();                       
                 String[] args = content.split(" ");



if (args[0].equalsIgnoreCase("!calculate")) {
                if (args.length == 1) {
                    channel.sendMessage("error message").queue();
                }else  {
                  String input = content;
                  input = input.replace(args[0], "");
                  double result = Double.parseDouble(text);
                  channel.sendMessage(result).queue();
                }
                }
}

after i put in a double.toString in between the result and the output as it wouldn't print the double.

              String output = Double.toString(result);
              channel.sendMessage(output).queue();

first attempt had no output! second had a "numberformatexception"! how do i solve this problem?

Dorus Blanken
  • 13
  • 1
  • 9
  • ideally, you should always catch wrong number strings. So like you already did for the empty string with throwing an error message you should also put the `Double.parseDouble(text);` in a `try-catch` block and return an error message if the second argument is not a proper number. – UninformedUser May 04 '19 at 07:47
  • Possible duplicate of [Method for evaluating math expressions in Java](https://stackoverflow.com/questions/7258538/method-for-evaluating-math-expressions-in-java) – Minn May 04 '19 at 12:13

1 Answers1

0

If you're getting a number format exception, you are probably trying to convert a string that has some other characters. Try to print "output" before converting it to a double and see what it looks like.

fion_
  • 47
  • 1
  • 7
  • Besides numerals the string contains operands (+, -, *, /) – Dorus Blanken May 04 '19 at 08:09
  • 1
    @DorusBlanken well, you never said that the string contains a Math formula ... I don't get why you just tried to parse it to a double value. How should this work, this method expects a single number. you have to write your own parser for the formula in your case. Or you keep it simple and just use one of the existing MAth evaluator for Java. Just search for "java math formula parser", there are dozens of libraries – UninformedUser May 04 '19 at 08:19
  • @DorusBlanken you should clarify this in your question – Minn May 04 '19 at 11:22