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.
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;
}
}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.
What about to use replaceAll java.lang.String method:
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[-1, -2, 455, 0, 4]
Description
[^-?0-9]+
[and]delimites a set of characters to be single matched, i.e., only one time in any order^Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.+Between one and unlimited times, as many times as possible, giving back as needed-?One of the characters “-” and “?”0-9A character in the range between “0” and “9”
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
java - How to get a number from an array? - Stack Overflow
java - How to retrieve values from an int array? - Stack Overflow
How to extract items out of an array in Java, and place into another array, and calculate a total - Stack Overflow
You can use a regular expression to extract numbers:
String s = "First number 10, Second number 25, Third number 123 ";
Matcher matcher = Pattern.compile("\\d+").matcher(s);
List<Integer> numbers = new ArrayList<>();
while (matcher.find()) {
numbers.add(Integer.valueOf(matcher.group()));
}
\d+ stands for any digit repeated one or more times.
If you loop over the output, you will get:
numbers.forEach(System.out::println);
// 10
// 25
// 123
Note: This solution does only work for Integer, but that is also your requirement.
Instead of replacing characters with empty string, replace with a space. And then split over it.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String line = "First number 10, Second number 25, Third number 123 ";
String numbersLine = line.replaceAll("[^0-9]+", " ");
String[] strArray = numbersLine.split(" ");
List<Integer> intArrayList = new ArrayList<>();
for (String string : strArray) {
if (!string.equals("")) {
System.out.println(string);
intArrayList.add(Integer.parseInt(string));
}
}
// what I want to get:
// int[0] array = 10;
// int[1] array = 25;
// int[2] array = 123;
}
}
As far as i understand the question, you are trying to get input from user. The input is the grades. Then you wanted to add up the grades and calculate the average of the grades.
public static double calculateAvg(List<Double>inputGrades){
List<Double> grades = new ArrayList<Double>(inputGrades);
double totalScore = 0.0;
double avgScore = 0.0;
if(grades !=null && grades.size()>0){
for(Double grade : grades){
totalScore = totalScore + grade;
}
avgScore = totalScore / grades.size();
}
return avgScore;
}
Taking user input and adding it to the list
List<Double> gradesList= new ArrayList<Double>();
gradesList.add(25.5);
gradesList.add(29.5);
gradesList.add(30.5);
gradesList.add(35.5);
System.out.println(calculateAvg(gradesList));
This would be a suitable solution too:
String[] input = JOptionPane.showInputDialog("What are your grades of this month?").split(" ");
double[] grades = new double[input.length];
double average = 0.0;
for (int i = 0; i < input.length; i++) {
// Note that this is assuming valid input
grades[i] = Double.parseDouble(input[i]);
average+=grades[i];
}
average /= grades.length;
So you could type in multiple "grades" seperated by a whitespace.
Just get digits with the Regex:
String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();
Find with Matcher all numbers and add them to the ArrayList. Don't forget to convert them to int, because m.group() returns the String.
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
And if your formula doesn't contain the second number, add there your desired default item.
if (numbers.size<2) {
numbers.add(1);
}
Finally print it out with:
for (int i: numbers) {
System.out.print(i + " ");
}
And the output for 3x^2 is 3 2.
And for the 8x it is 8 1.
if the numbers are allways separated by x^, just split the string using this separator
String[] splitted = "3x^2".split("x\\^");
First split the string. Then parse each element in String array to new array
String[] s=str.split("\\D+");
int[] intarray=new int[s.length];
for(int i=0;i<s.length;i++){
intarray[i]=Integer.parseInt(s[i]);
}
Just split your input according to one or more non-digit characters and then convert the datatype of each element to integer.
String[] parts = str.split("\\D+");
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.
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:
- Have you thought about a for loop instead of a while loop? All of your cases increment the index by 1.
- Do you know how the input string should be formatted, in which case you could use a regular expression to extract the numbers.
- You have used isDigit once, why have you mixed it with the >= <= solution? What about the letters?
Use a regex (see Pattern and matcher):
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(<your string here>);
while (m.find()) {
//m.group() contains the digits you want
}
you can easily build ArrayList that contains each matched group you find.
Or, as other suggested, you can split on non-digits characters (\D):
"blabla 123 blabla 345".split("\\D+")
Note that \ has to be escaped in Java, hence the need of \\.
You can use String.split():
String[] nbs = str.split("[^0-9]+");
This will split the String on any group of non-numbers digits.
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);
}
}
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.