1

So hey guys, I'm creating a calculator because I searched on google what's a good starter program to create when learning java and calculator appeared. Yes I'm pretty new to java so please bear with me.

Here below is a snippet of what I wanted something to be done. I've got problems of trying to create a backspace button. This is the part where when I click the button then it will do something. result here is the value of my jtextfield. What I want the jbutton to do is to delete one character/number from the jtextfield. I tried value = value.length() - 1; and realized that I can't subtract 1 from a string lol. Does anyone have any idea and help a newbie out?

private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {                                          
          String value = result.getText();    
            value = value.length() - 1;

            result.setText(value);
    }     

Extra: ~ Oh and also, can somebody give me a tip on how, in the simplest way, so that when I click the + button from the calculator then it would add the first number(s) inputted and the second number(s) inputted. It would be pretty much appreciated! Thanks.

Nolan Kr
  • 81
  • 12

3 Answers3

2

All you need to do is use substring():

String value = result.getText();    
String newValue = value.substring(0, value.length() - 1);

result.setText(newValue);
Juliano Alves
  • 2,006
  • 4
  • 35
  • 37
  • Thanks ! this helped me a lot! I'm kinda confused though with the code but I'll try and study it since I'm trying to learn. Anyways, thank you again! – Nolan Kr Nov 22 '16 at 12:08
  • No worries, I know how hard it can be in the beginning! Just remember to upvote the useful answers! :) – Juliano Alves Nov 22 '16 at 12:14
1
String value = "abc";
System.out.println(value.substring(0, value.length() - 1));

Try this.

FallAndLearn
  • 4,035
  • 1
  • 18
  • 24
1

Extra question:

If I understand your question correctly, you type in the values in a field and get them as strings. So if you were to type two numbers separated by a blankspace, this should work.

String input = "12 3";
String[] numbers = input.split(" ");

int sum = Integer.parseInt(numbers[0]) + Integer.parseInt(numbers[1]);
System.out.println(sum);

OUTPUT -> 15

Alex Karlsson
  • 296
  • 1
  • 11
  • So the space over there is a splitter? :o wow that's a great idea. I also had an idea of creating two variables and storing numbers there but i don't know how to separate after clicking the add button xD I'll try this out! Thanks! – Nolan Kr Nov 22 '16 at 12:17
  • The split method takes whatever regex you take and split with that, so in this example a blankspace " ". You could also have a string like "12.3" and use split(".") to get out the substrings "12" and "3". Hope it works for you :) – Alex Karlsson Nov 22 '16 at 12:21