Reputation: 15
I want to somehow store the text from JTextField into array and then sum it.
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//fldi is the JTextField I want to get text from
int ii = Integer.parseInt(fldi.getText());
}
});
What should I do next? how can I split text from there, for example if user input is "256" I think it should be stored in array like "2", "5", "6".
EDIT: So after Jake Miller's help I've got:
String input = fldi.getText();
int sum = 0;
int[] values = new int[input.length()];
for(int i = 0; i < input.length(); i++) {
int number;
if(input.substring(i, i+1).equals("-")) {
number = Integer.parseInt(input.substring(i, i+2));
} else {
number = Integer.parseInt(input.substring(i, i+1));
}
values[i] = number;
sum = sum + values[i];
}
fldwo.setText(Integer.toString(sum));
But when I try it for negative numbers like "-2" and "-1" values array stores 4 values "-2", "2", "-1", "1" and the sum at the end is 0, but it should be -3.
Upvotes: 0
Views: 1003
Reputation: 2642
Don't parse it right away. Store the input into a String, use a loop to use .substring() to go through each character in the String, and parse each individual number and store into an int array.
String input = fldi.getText();
int[] values = new int[input.length()];
for(int i = 0; i < input.length(); i++) {
values[i] = Integer.parseInt(input.substring(i, i+1));
}
If they input 256, then the array will have 3 values: 2, 5, and 6
EDIT
For negative numbers, you'll need to have a check for the character "-" as it indicates a negative number. Then, you'll use substring(i, i+2)
to take two characters as opposed to one (the - and the number itself). You also don't need the array. You can simply add each number you parse to the sum directly. You also should use a while loop and increment i on your own. If you find a negative number, you're using 2 characters, which means you need to increment i by two instead of 1.:
int sum = 0;
int i = 0;
while(i < input.length()) {
int number;
if(input.substring(i, i+1).equals("-")) {
number = Integer.parseInt(input.substring(i, i+2));
i += 2;
} else {
number = Integer.parseInt(input.substring(i, i+1));
i++;
}
sum += number;
}
An example:
A user inputs 125-35
. The first three characters will NOT be equal to "-", therefore they'll simply be parsed and stored into the values array. Once you reach the 4th character (3rd index), the character will be a "-", so the if statement will cause number to be equal to -3 as the substring now returns two characters as opposed to one.
Upvotes: 1