Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
  System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

Answer from Sean Owen on Stack Overflow
🌐
Reddit
reddit.com › r/javahelp › how do i extract numbers in an array to another array?
r/javahelp on Reddit: How do I extract numbers in an array to another array?
June 22, 2018 -

Okay, so seems kinda weird. Here's what the assignment says. Don't worry I'm not asking anyone to do this its just a weird description.

"Write a program that generates 100 random integers in the range 1 to 100, and stores them in an array. (did this)Then, the program should call a class method that extracts the numbers that are even multiples of 4 into an array and returns the array. (did this somewhat)The program should then call another method that extracts the numbers that are not even multiples of 4 into a separate array and returns the array. (same as previous) Both arrays should then be displayed.(not sure how)."

Now, I'm not asking anyone here to solve it, but I'm not sure how to return the numbers that are results of each method into new arrays, which can later be displayed. Here's what I have. My method only gets the total count of each of the integers, and I feel like I am really close. Let me know how I could go about doing this. Thanks...

public class Unit8Assignment {
	public static void main (String [] args)
	{
		int array [] = new int [100];
		int array2 [] = new int [100];
		
		for (int j=0 ; j< array.length; j++)
		{
			array [j] = (int)((Math.random() *100)+1);
			//System.out.print(array[j]);
		} 
	array2=array;
		
		int returned1 [] = even(array);
		int returned2 [] = notEven(array);
		
	}
	
	public static int[] even(int newArray[]) {

		int k = 0;

		for (int i = 0; i < newArray.length; i++) {

			if (newArray[i] % 4 == 0 && newArray[i] % 2 == 0) {
				k++;
			}
		}
		System.out.print(k);

		System.out.println();

		return newArray;
	}
	public static int [] notEven( int newArray2[] )
	{
	
	int k = 0;
	
		
			for (int i = 0; i < newArray2.length; i++)
			{
				
			
				if (newArray2[i] % 4 != 0)
				{
					k++;
				}
			}
System.out.println(k);
	
			
			return newArray2;
		}
			

}
Top answer
1 of 3
2
I think the problem with setting the even and not-even arrays with a length of 100, and the fact that you just slip the numbers into the matching indices, means you’re going to have a lot of 0s in your array. This is because (if I remember correctly) when you initialize the array it just slips a 0 into all elements and we know that they both will not have a full 100 numbers inputted from the original array. I think they want you to make an array with only the numbers you put in it. Like if only 4 of the original array are inputted to the even array, the even array’s length should be 4. So you should focus on learning how the create a dynamic array. Did the assignment specify what kind of arrays/classes to use? When I was learning Java my teacher was always making us create methods for dynamic arrays even though Java already has classes for that like Lists (was a great learning experience though). Also - why do you create array2? I don’t see the point of it and I didn’t see it used anywhere.
2 of 3
2
It's hard to understand how the teacher wants you to solve this. It could easily be done with Collections (like an ArrayList), but I suspect you haven't covered that topic yet and you are not expected to use them. That being said, there is one place where you seemed confused. The parameter of your methods are called newArray, but they actually aren't new arrays. The array your method receives is the very same that the caller provided as argument. So if I look at your even method, you have sucessfully counted how may "multiple of four" the array contains. Now you just need to create an array of that size by doing int[] actuallyANewArray = new int[k];. Then you would need to loop again on the original array, redo the if statement, and add the values when applicable. Then return that new array. Also, all multiples of 4 are even :-) I think your teacher is messing with you there.
Discussions

java - How to extract numbers from an array list, add them up and divide by the amount of numbers in the array list? - Stack Overflow
I was watching a lesson online about arrays. It taught me the 'basics' of array lists: how to create an array list. So I was wondering, how would one go about creating an array list from the users'... More on stackoverflow.com
🌐 stackoverflow.com
April 28, 2016
java - How to get a number from an array? - Stack Overflow
question: Suppose this is the number in my array {1,2,3,4,5,6,7,8} and each number is a position like :: 1=1 ,2=2 , 3=3, 4=4, 5=5, 6=6, 7=7, 8=8 It is not an array position just the More on stackoverflow.com
🌐 stackoverflow.com
java - How to retrieve values from an int array? - Stack Overflow
Trying to revise my concepts for Java array and print after generating numbers between min and max value and trying to extract the numbers stored in the array however get it as zero however length ... More on stackoverflow.com
🌐 stackoverflow.com
How to extract items out of an array in Java, and place into another array, and calculate a total - Stack Overflow
Firstly, I'm doing this for one of my assignments, and I don't expect to be spoon fed. Just some guidance in the correct direction would be great. I'm required to code a java application which ope... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Java2s
java2s.com › example › java › java.lang › extract-integer-values-from-an-array-of-strings-into-an-array-of-int.html
Extract integer values from an array of strings into an array of int. Exceptions in the format of the string are trapped and 0 value(s) returned. - Java java.lang
ja va 2s.co m /** * <p>Extract integer values from an array of strings into an array of int.</p> * * <p>Exceptions in the format of the string are trapped and 0 value(s) returned.</p> * * @param src an array of strings, each of which should be an integer numeric value * @return an array of int */ static public int[] copyStringToIntArray(String[] src) { if (src == null) return null; int n = src.length; int[] dst = new int[n]; for (int j = 0; j < n; ++j) { int value = 0; try { value = Integer.valueOf(src[j]).intValue(); } catch (NumberFormatException e) { } catch (NullPointerException e) { } dst[j] = value; } return dst; } }
🌐
Blogger
hiromia.blogspot.com › 2016 › 07 › how-to-get-extract-numbers-or-digits-or.html
Hiro Mia: How to get extract numbers or digits or numeric values and numbers array from a string in Java
import com.google.common.base.CharMatcher; import java.util.Arrays; public class Getnumbers { // Get extract numbers from String public static String getAllNumberfromString(String input) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length(); i++) { final char c = input.charAt(i); if (c > 47 && c < 58) { sb.append(c); } } return sb.toString(); } // Get only Numbers from String public static String getExtractDigits(String src) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < src.length(); i++) { char c = src.charAt(i); if (Character.isDigit(c)) { bu
🌐
Stack Overflow
stackoverflow.com › questions › 56025648 › how-to-get-a-number-from-an-array
java - How to get a number from an array? - Stack Overflow
You need a modulo operator (%) to identify numbers in odd positions and a while loop (iterate while array.length >= 2) – Arnaud Denoyelle Commented May 7, 2019 at 15:21 · Note : you can also do it without a modulo if you use a for loop where you increment the index by 2 instead of 1. – Arnaud Denoyelle Commented May 7, 2019 at 15:23 · In Java, array indexes start at 0.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 26075355 › how-to-extract-items-out-of-an-array-in-java-and-place-into-another-array-and
How to extract items out of an array in Java, and place into another array, and calculate a total - Stack Overflow
Below is the code I have written so far which opens the text file, and places each line from the text file into an array item. package accountFilesDemo_17259747; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; /** * This below is an the full path used for user to enter * path to grades * C:\\Users\\Vick\\PT\\accountFilesDemo_17259747\\src\\accountFilesDemo_17259747\\Grades.txt * yours (the markers) will be different * @author vkumar * */ public class StudentGPA_17259747 { public static void main(String[] args)
🌐
Stack Overflow
stackoverflow.com › questions › 74292560 › in-java-how-can-i-extract-a-number-in-the-array-and-store-it-in-a-var-and-remove
In java how can I extract a number in the array and store it in a var and remove it from the original arr - Stack Overflow
I tried this but I can't use the ArrayUtils.remove because I can't figure out how to import apache commons on replit which my teacher is making me use ... double sum = 0; for (int i = 0 ; i < arr.length ; i++){ if (arr[i] != max){ sum += Math.pow(arr[i],2); } } return (sum == Math.pow(max, 2)); This solution assumes that all side lengths are > 0 ... Find the answer to your question by asking.
🌐
Stack Overflow
stackoverflow.com › questions › 69730277 › how-to-extract-all-integers-from-a-string-and-store-them-in-an-int-array-in-java
How to extract all integers from a string and store them in an int array in java - Stack Overflow
... It's a one-liner: Strip leading and trailing non-digits, then split on non-digit/minus, convert to int then collecting to an array: int[] numbers = Arrays.stream(str.replaceAll("^\\D+|\\D+$", "").split("(?=-\\d)|[^-\\d]+")) .mapToInt(In...
🌐
codelessgenie
codelessgenie.com › blog › how-to-extract-numbers-from-a-string-and-get-an-array-of-ints
How to Extract Numbers from a String into an Integer Array in Java with Regular Expressions — CodeLessGenie.com
Before diving into code, let’s clarify the goal: Given a string (e.g., "The price is $100, discount 20; final: 80"), extract all integer values (e.g., 100, 20, 80) and store them in an int[] array. ... Integers only: We focus on whole numbers (positive, negative, or zero).
Top answer
1 of 3
1

Start by separating your code into input handling, computation, and output. Each of those could have its own method(s).

For the input, you're working too hard. The java.util.Scanner has methods to give you ints.

Think about what the inputs and outputs of each function should be. For example, your input handling function should take an InputStream and return a List of Integers or an array of ints.

2 of 3
1

What @jmoreno has said is pretty much spot on but seeing as this is a java problem remember that the convention is to use lower case letters for method names.

The important things to remember are that each method should be simple, readable, encapsulate a unit of work and be easily testable. Again, following what @jmoreno has said and considering the gatherInput method, you can take the first five lines of code and create a new method that returns your string input. If you are using Eclipse this is very easy, highlight the code and click Alt+Shift+M which will open the 'Extract Method' refactor dialog box.

The loop is the only real place where you have to think a little more as currently it is doing multiple jobs, but if you break out the code that extracts the numbers (extractIntegers(input)) then the rest becomes easy - you should also be able to remove the additional index == input.length() test.

Other considerations:

  1. Have you thought about a for loop instead of a while loop? All of your cases increment the index by 1.
  2. Do you know how the input string should be formatted, in which case you could use a regular expression to extract the numbers.
  3. You have used isDigit once, why have you mixed it with the >= <= solution? What about the letters?
🌐
Stack Overflow
stackoverflow.com › questions › 63538769 › how-to-extract-positive-numbers-from-one-array-and-move-them-to-another-in-java
How to extract positive numbers from one array and move them to another in Java? - Stack Overflow
August 22, 2020 - public static void main(String[] args) { int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87}; int l = array.length; int[] arrayPositive = new int[l]; int[] arrayNegative = new int[l]; int i,j,k; i=j=k=0; for (i = 0; i < l; i++){ if (array[i] > 0) { arrayPositive[j]=array[i]; ++j; } else if(array[i] < 0){ arrayNegative[k]=array[i]; ++k; } } for (i = 0; i < l; i++){ System.out.println(arrayPositive[i]+"\t" + arrayNegative[i]); } } ... Sign up to request clarification or add additional context in comments. ... If you want to extract positive numbers, your if should check whether each array element is greater than 0, like in the following code.
🌐
Quora
quora.com › How-do-you-extract-numbers-from-a-string-in-Java
How to extract numbers from a string in Java - Quora
Answer (1 of 3): You can extract numbers from a string in Java using two methods. Method 1: Using the in-built method Character.isDigit() The Character.isDigit() method determines whether the character is a digit or not. So you traverse the string, get each character one by one and check if it ...
Top answer
1 of 2
1

An example of a reasonable Student class design could be something like this (implementation left blank):

import java.util.List;
import java.util.ArrayList;

public class Student {
    private String name;
    private List<Double> grades;

    public Student(String name) {
        // TODO 
    }

    public void addGrade(double grade) {
        // TODO
    }

    public double average() {
        // TODO 
    }

    public String toString() {
        return String.format(
            "Student: %s\nAverage Grade: %f\n", 
            this.name, 
            this.average()
        );
    }
}

class TestStudent {
    public static void main(String[] args) {
        Student s = new Student("Hunter");
        s.addGrade(100);
        s.addGrade(90);
        s.addGrade(0);
        s.addGrade(85);
        s.addGrade(75);
        System.out.println(s);
    }
}
2 of 2
0

Using the code as you currently have:

Object[][] database = new Object[14][5];

We can add a few things to make it more friendly to the reader

final int STUDENTS = 14;
final int GRADES = 4;
Object[][] database = new Object[STUDENTS][GRADES + 1];

In order to be able to check the average values

public double getStudentAverageGrade(Object[] student)
{
    for(int i = 0; i < GRADES; i++) // forEach grade
    {
        gradesSummatory += (double) student[i + 1]; // plus one is added since we ignore first value (which is students name)
    }
    return gradesSummatory/GRADES;
}

Now, to be able to see the average of ALL the students, its just easier since we simply have to implement the method previously created.

public double getAverageGrade()
{
    double avgSummatory = 0;
    for (int i = 0; i < STUDENTS; i++)
    {
        avgSummatory += getStudentAverageGrade(database[i]);
    }
    return avgSummatory/STUDENTS;
}

By saying this I don't consider it being a really optimal solution (you could sum all the elements and divide only once) but it's the most expressive non-object oriented solution imo. I'd rather abstract these elements/objects into different classes such as Student so as to reuse code as much as possible. But for this case, this could do the trick.

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-extract-digits-from-a-given-integer
Java Program to Extract Digits from A Given Integer - GeeksforGeeks
July 23, 2025 - The same process is iterated till the end is extracted. So, In this approach, the last digit from the number and then remove it and is carried on till reaching the last digit. Take the integer input. Finding the last digit of the number. Print the last digit obtained and then remove it from the number. Keep on following the step 2 and 3 till we reach the last digit. Below is the implementation of the above approach: ... // Java program to Extract Digits from A Given Integer // Importing Libraries import java.util.*; import java.io.*; class GFG { // Main driver function public static void main(