I'm new to Java so I have given myself small projects to help myself learn the ropes of java. My project was to create a function that would summate an expression no matter how high the degree or value of n
.
I ended up being able to complete it but I wanted someone who knew what they were doing to look over it and see if I was doing things the right way.
A goal was to use no pre-built packages but I ended up using the java.lang.Math.pow()
function (I didn't import it).
Also, what recommendations do you have for learning for beginners? I do have some experience programming but I feel like I never learned the correct way...
Code:
package TestSpace;
public class MathClass {
/*
Steps:
1. Get array of any length and n
2. Reverse list so highest degree coefficients are last
3. Run for loop for each time n increases
4.Run for loop inside of that for each entry in array
*/
//args consists of the coefficients of x; must include all degrees of x counting down from the highest degree
public static float sigma (int[] args, int n) {
float value = 0;
int length = args.length;
//reverses list
int[] reverselist = reverselist(args);
for(int i = 1;i<n+1;i++) {
for(int v = 0; v < length;v++) {
// Multiplies coefficient by "x" raised to the power of its degree
value += reverselist[v] * java.lang.Math.pow(i, v);
}
}
return value;
}
//Reverses the order of the given array so that highest degree is at the end
public static int[] reverselist(int[] args) {
int length = args.length;
int[] newint = new int[length];
for(int i = 0;i<length;i++) {
newint[i] = args[length - (i+1)];
}
return newint;
}
//Makes printing simple
public static void print(Object obj) {
try {
System.out.println(obj);
}catch(Exception e){
System.out.println(e);
}
}
//main function
public static void main(String[] args) {
print(sigma(new int[] {5,2,7,4},4));
}
}