This question already has answers here:
Finding numbers in a text and summing them
(2 answers)
Closed 6 years ago.
I want to get the sum of all numbers from a JTextField. I'am using this code but it doesn't work. The problem is that is that I can't get the {d1} as numbers from the JTextField.
String a = jTextField1.getText();
int d1= Integer.parseInt(a);
int Arry[] = {d1};
int sum = 0;
for ( int i = 0; i<Arry.length; i++ )
{
sum=sum + Arry[i];
}
jTextField2.setText(sum+"");
If jTextField1 contains not only numbers, you may want to extract all the digits like this:
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(jTextField1.getText());
List<Integer> numbers = new ArrayList<>();
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
then sum the numbers:
int sum = 0;
for (Integer number : numbers)
sum += number;
If you can guarantee that the JTextField will only contain input that can be parsed into ints, e.g. no letters or symbols, then the only possible remaining issue is whitespace between your numbers. I would suggest that you go to the Pattern API and look for characters that can detect whitespace and then go to String API and find a method that can split a String based on an input regular expression (regex). Then from there you can easily parse the split String into ints and get your sum. For example:
String a = jTextFieldName.getText();
String[] storage = a.someSplittingMethod("whitespace regex");
int sum = 0;
for(int c = 0; c < storage.length; c++)
sum += Integer.parseInt(storage[c]);
Related
easy for usual numbers, but telephone numbers can start with 01-...., as an example, 01234
is basically 1234 for java, right?
So I can't divide by 10 recursively to find out how many digits there are.
is there any different way to find out how many digits there are ?
thanks in advance.
ps.: no regex if possible
Assume that the phone number is a string,
String pn = "049-4912394129" // that's a random value
then you could iterate in that string and check if a character is indeed a number
int count = 0;
for(char c : pn.toCharArray()){
if(Character.isDigit(c))
count++;
}
As you phone number is an int, you don't need to bother with regex and every locale phone number patterns.
Simply convert your intphone number to a String. Then you can easily get the string length.
int myIntNumber = 1234;
String myStringNumber = String.valueOf(myIntNumber);
int length = myStringNumber.length();
If you are talking about a number that represented by a String object then:
public int getNumberOfDigits(phoneNumber) {
int count = 0;
for (int i = 0, i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
count++;
}
}
System.out.println("Number of digits: " + count);
return count;
}
If you are talking about a number that represented by an int then simply
convert it to String before using it like so:
String phoneNumber = String.valueOf(phoneNumberInInt);
I assumed you DO want to count the zeros as a digit because you are not summarizing the value of them, so they do have a meaning when you talk about how many digits are there.
this could easily be done with a lambda
"049-4912394129".codePoints().filter( Character::isDigit ).count(); // 13
I am writing a groovy program. I have an output like below
red 5green 5blue 10white 15
I want to sum up the digits in the output. The sum would be 35
I wrote the below logic however the program returned 17 which is right as the below logic takes into account digits.
can you please guide me as to how I make the program understand two digit numbers? so that i get the right sum?
for (int i =0; i < output.length(); i++)
{
{
sum=sum+Character.getNumericValue(grps.charAt(i))
}
}
Thanks
Since you tagged for [groovy] too:
You could "findAll" number-strings in the string with a regexp /\d+/, turn all of them into numbers, and finally sum() them. e.g.
def sumNumberStrings(s) {
s.findAll(/\d+/)*.toLong().sum()
}
assert 35==sumNumberStrings("red 5green 5blue 10white 15")
I would use a regular expression to replace all non-digits with a space, trim() that to remove any leading and trailing and white-spaces and then split on (optionally consecutive) white-space; like,
String output = "red 5green 5blue 10white 15";
int sum = 0;
for (String token : output.replaceAll("\\D+", " ").trim().split("\\s+")) {
sum += Integer.parseInt(token);
}
System.out.println(sum);
Outputs (as requested)
35
Another option would be a Pattern to find all sequences of one or more digits and group them, then use a loop to parse and add to the sum. Like,
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(output);
while (m.find()) {
sum += Integer.parseInt(m.group(1));
}
System.out.println(sum);
Which will also give you 35.
Apparently I can't write code in comment, but just to follow on with the answer you could take it a bit further and using slashing strings, drop the semicolons and the System.out.
String output = "red 5green 5blue 10white 15"
int sum = 0
for (String token : output.replaceAll(/\D+/, " ").trim().split(/\s+/)) {
sum += Integer.parseInt(token)
}
println(sum)
A simple algorithm that does not require usage of regular expressions or other complicated features would be something like this:
String output = "red 5green 5blue 10white 15";
// The result
int sum = 0;
// Sum of the current number
int thisSum = 0;
for (char c : output.toCharArray()) {
// Iterate through characters
if (Character.isDigit(c)) {
// The current character is a digit so update thisSum so it includes the next digit.
int digitValue = c - '0';
thisSum = thisSum * 10 + digitValue;
} else {
// This character is not a digit, so add the last number and set thisSum
// to zero to prepare for the next number.
sum += thisSum;
thisSum = 0;
}
}
// If the string ends with a number, ensure it is included in the sum.
sum += thisSum;
System.out.println(sum);
This works with numbers of any number of digits.
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
Examples of the String
131-5923-213
1421-41-4-12-4
1-1
How would I extract the integers into an Array or find the sum of these integers? My code so far goes
int hyphenCount = socialNum.length()-socialNum.replaceAll("-", "").length();
ArrayList<Integer> sum = new ArrayList<Integer>();
for(int i = 0; i < hyphenCount; i++)
{
//my brain is too small
}
What I want to do is make a function like the following
public void extractSum(String s)
{
int outputSum;
//stuff
return outputSum;
}
Using Streams you can do:
int sum = Arrays.stream(str.replace("-", "").split("")).mapToInt(Integer::valueOf).sum();
Which will replace the hyphen and then split each character, parse the integer, and return the sum
Output: (For the String "131-5923-213")
30
If you want the sum of 131 + 5923 + 213 you could do:
int sum = Arrays.stream(str.split("-")).mapToInt(Integer::valueOf).sum();
Which will split on a hyphen, parse the integers, and return the sum
Apart from #GBlodgett's answer using stream, you could simply run a for loop to calculate the sum.
String string = "131-5923-213";
String[] num = string.split("-"); //<----num[0] = "131" ,num[1]="5923",num[2] = "213"
int hyphenCount = num.length; //<----it would give you 3 as length
int mySum = 0; //initialize the sum as 0
for(int i = 0; i < hyphenCount; i++)
{
mySum+= Integer.parseInt(num[i]); //<---convert the string to an int
}
Output: 6267
I'm working on a school project in Android Studio and I've already asked here how to randomly generate equations, like 10+48*4. Someone suggested me this code to generate the equations:
String[] operationSet = new String[]{"+", "-", "/", "*"};
public void testGenerateRandomEquations() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(3)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(Integer.MAX_VALUE) - random.nextInt(Integer.MAX_VALUE);
numbers.add(number);
}
//Now you've the list of random numbers and operations. You can further randomize
//by randomly choosing the number and operation from those list.
}
But now I don't know how to display the generated equation. How can I display the equation for example in a TextView?
Maybe I'm just too dumb to understand but it would be nice if someone could help me :)
Here is the link to the original post: http://stackoverflow.com/a/39960279/6949270
All you have to do is to loop over the two lists - numbers and operations and concatenate them into a single string:
String equation = null;
for (int i = 0; i < numOfOperatrions; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1); //Add the last number to the equation
The last line is needed because there are more numbers (one more) than operations.
It is better to use StringBuilder than String when concatenating strings, but for short strings it's OK.
EDIT - Why does it work?
We are concatenating String with an Integer, using the + operator.
The JAVA compiler converts in this case the Integer into a String, so no other casting is required.
This question already has answers here:
Convert an integer to an array of digits
(24 answers)
Closed 7 years ago.
How would I split a binary number up by each individual digit and then put it into a java list back to front.
For example:
Binary Number:
01111101
After it is split up it would look like
int[] binary = {0,1,1,1,1,1,0,1}
After it the array is flipped it would look like
int[] binaryFlipped={1,0,1,1,1,1,1,0}
I am doing this so that I can convert a binary number into a denary number in java.
So i would take the flipped list the for each binary digit work out it's denary value. This is an example of ruffle how i would do it. (Note: lengthOfList is not the write method but is just there for an example of how it would work)
For(x=0;lengthOflist(binary);x++){
sum=binary[x]*pow(2,x)+sum;
}
System.out.println(sum);
Assuming that your input is an int and not a String:
int number = 2;
int[] binaryFlipped = new int[8];
for (int i = 0; i < binaryFlipped.length; i++) {
binaryFlipped[i] = number % 2;
number = number >> 1;
}