Externally store tools in Java project - java

I've written the following code to solve problem 1 which is to simply calculate the total of all multiples of 3 and 5 below 1000. (I realize I don't need the constructor, I just included it for practice).
public class p1multiplesOf3and5 {
public p1multiplesOf3and5() {
//Constructor
}
public int sumArray(int[] Array){
int sum = 0;
for (int item: Array) {
sum += item;
}
return sum;
}
public int sumMultiples3and5(int limit) {
int[] multiples = new int[limit];
int count = 0;
for (int i=1; i<limit; i++){
if (i%3==0 || i%5==0) {
count++;
multiples[count] = i;
}
}
int total = sumArray(multiples);
return total;
}
public static void main(String args[]) {
p1multiplesOf3and5 x = new p1multiplesOf3and5();
int t = x.sumMultiples3and5(1000);
System.out.println("Total is: " + t);
}
}
My question is based around the sumArray method I created and used. I have a background using MATLAB, and in some projects I've created a +tools folder for example, and would save this as a function within that folder. Any time I wanted to use it I could write tools.sumArray() to call it.
Is there a similar process for this in Java? As I feel this is a method I might use elsewhere and could be useful to have easy access to it, and any others I create.

Basically you want to create a utility class which contains sumArray(). If you're using it within one project only, you can create a class called Utils and add a static method that does:
public class Utils {
public static int sumArray(int[] Array){
int sum = 0;
for (int item: Array) {
sum += item;
}
return sum;
}
}
so that you can use it later on in the following way:
int[] myArray = {1,2,3,4,5};
int sum = Utils.sumArray(myArray);
But the jdk 8 already has something like that, so you could avoid re-inventing the wheel:
Arrays.stream(myArray).sum();

Related

How do I pass the array to the main method after calculating the sum of values?

So this is the code I currently have. I am trying to calculate the sum of all the numbers in the second method and then return it to the main method to display but I am getting confused with how to do this properly. Any help is welcome!
public class Main {
public static void main(String[] args) {
int[] population = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
int[] total = computeTotal(population);
for (int i = 0; i < total.length; i++);
System.out.print(total + " ");
}
public static int computeTotal(int[] population) {
int[] population2 = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
return population2;
}
}
If want to calculate sum via method, you can just return an integer.
public static void main(String[] args) {
int[] population = { 693417, 457502, 109985, 107360, 103773, 13145, 5469 };
int total = computeTotal(population);
System.out.print(total + " ");
}
public static int computeTotal(int[] Popu) {
int sum=0;
for(int i=0;i<Popu.length;i++)
sum+=Popu[i];
return sum;
}
By the way the for loop you write is going to do nothing because it just run length times with no command according to ; is the first command each time the executing loop see .
You should write like this
for(int i=0;i<Popu.length;i++)
only one line code end with ;
or
for(int i=0;i<Popu.length;i++){
...
}
to run mutiple code.

Return the result of each iteration in the loop

I'm doing something that produces the right result. However, it is wrong from a design POV.
The point of the program is to list the result of all the powers of a number up to and including the user-defined limit.
I have a constructor which accepts the base and the exponent from the Scanner. Then a method, which utilises a for loop to calculate the power for each exponent.
Now, the problem is that I'm printing the result from each loop iteration directly from this method. This beats the point of private variables and it being void in the 1st place.
Therefore, I want to define a getter method which returns the result of each power to the output. I used to set them just fine for if/switch statements, but I don't know how to do the same for loops. If I assign the result to a variable within the loop and return that variable from the getter then it will return only the output from the final iteration.
Private implementation
package Chapter6Review;
public class Powers {
private int target;
private int power;
public Powers(int target, int power) {
this.target = target;
this.power = power;
}
public void calculatePower() {
for (int i = 0; i <= power; i++) {
System.out.println((int) Math.pow(target, i));
}
}
/*
public int getPower() {
return
}
*/
}
User interface
package Chapter6Review;
import java.util.Scanner;
public class PowersTester {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your base: ");
int target = in.nextInt();
System.out.print("Enter your exponent: ");
int power = in.nextInt();
Powers tester = new Powers(target, power);
tester.calculatePower();
}
}
You can simply use a List ;
public List<Integer> calculatePower() {
int p;
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i <= power; i++) {
p = (int) Math.pow(target, i);
result.add(p);
}
return result;
}
Then in you main method, you can iterate the list to print the powers like that :
List<Integer> result = new ArrayList<Integer>();
Powers tester = new Powers(target, power);
result = tester.calculatePower();
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
You could store each of the results in a List:
List<Power> list = new ArrayList<>();
and when you call it add it as well
list.add(new Powers(target, power));
At the end you can iterate over the list like this:
for (Power power : list){
// your code
}
You might consider using streams as well
public List<Integer> calculatePower() {
return IntStream
.rangeClosed(0, power). // iterate from 0 till power inclusive
.mapToObj(i -> (int) Math.pow(target,i))
.collect(Collectors.toList()); // get result as list
}
Thanks for all the answers. Using a list seems to be a good choice.
Since I haven't covered lists yet, I resorted to this solution for now. But I don't like having code that can affect the solution in the main. Ideally, the loop should go in the private implementation.
Main
Powers tester = new Powers(target, power);
for (int i = 0; i <= power; i++) {
tester.calculatePower(i);
System.out.println(tester.getPower());
}
Private implementation
public void calculatePower(int iPower) {
result = (int) Math.pow(target, iPower);
}
public int getPower() {
return result;
}

Does java escape analysis also work for arrays with only one element?

Background:
When you extract methods out of long code pieces, you often run into the call-by-value problem with primitive variables. You cannot change those primitive parameters in the extracted method so that the caller sees the changes.
You can avoid that by making the primitive variable an array with only one element. Then it is effectively used call-by-reference. However it is now an object on the heap. Is the escape analysis of Java clever enough to understand that and use the stack despite that?
Given following code and the case it could not be inlined:
public class EscapeAnalysisTest {
public static void main(String[] args) {
final Set<Integer> integers = new HashSet<>();
integers.add(1);
integers.add(9);
integers.add(8);
integers.add(4);
// and so on ...
final long[] product = new long[1];
final long[] sum = new long[1];
final long[] count = new long[1];
final int[] max = new int[1];
final int[] min = new int[1];
product[0] = 1L;
max[0] = Integer.MIN_VALUE;
min[0] = Integer.MAX_VALUE;
for (Integer i : integers) {
calcSomeValues(product, sum, count, max, min, i);
}
System.out.println("Product :" + product[0]);
System.out.println("Sum :" + sum[0]);
System.out.println("Count:" + count[0]);
System.out.println("Max:" + max[0]);
System.out.println("Min:" + min[0]);
}
private static void calcSomeValues(final long[] product, final long[] sum, final long[] count, final int[] max,
final int[] min, Integer i) {
product[0] *= i;
sum[0] += i;
count[0]++;
max[0] = Math.max(max[0], i);
min[0] = Math.min(min[0], i);
}
}
Here's a better way to do this:
public class Test {
public static class Summary {
private long product;
private long sum;
private long count;
private int max;
private int min;
private Summary() {
product = 1;
sum = 0;
count = 0;
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
}
public long getProduct() { return product; }
public long getSum() { return sum; }
public int getCount() { return count; }
public int getMax() { return max; }
public int getMin() { return min; }
public static Summary summarize(Collection<Integer> ints) {
Summary s = new Summary();
s.count = ints.size();
for (Integer i : ints) {
s.product *= i;
s.sum += i;
if (i > s.max) {
// You can use Math.max if you want
s.max = i;
}
if (i < s.min) {
// You can use Math.min if you want
s.min = i;
}
}
return s;
}
}
public static void main(String[] args) {
final Set<Integer> integers = new HashSet<>();
integers.add(1);
integers.add(9);
integers.add(8);
integers.add(4);
// and so on ...
Summary s = Summary.summarize(integers);
System.out.println("Product: " + s.getProduct());
System.out.println("Sum: " + s.getSum());
System.out.println("Count: " + s.getCount());
System.out.println("Max: " + s.getMax());
System.out.println("Min: " + s.getProduct());
}
}
Using arrays the way you have is just weird. Don't do it. This will confuse other programmers and isn't how the language is intended to be used. It violates the Principle of Least Astonishment.
Instead, find a way to make the system work for you without going into weird territory. You have multiple values that are logically associated with each other, and they're all computed at the same time. When you have several values that are used together, it's a good time to think about using a class. By using a class and a single method that does all the updating, your code is clear and sensible. The class I've provided actually ends up being immutable (as far as external code is concerned) because the logic of computing the summary is all inside the summarize method, which has access to the private attributes, so it's very well encapsulated. (The names could probably be better, but I think this is good enough as an example.) If modifying the private state in summarize is undesirable, this can be easily adapted by giving Summary arguments with the values of its instance variables and simply passing the values into the constructor after computing them as local variables, which would turn Summary into a very simple result object.
Keeping all this logic very localized and preventing callers from modifying the result makes it very easy to reason about what's going on. Your example code with length one arrays violates both of those principles and makes it harder to understand, use, or maintain the code.
Alternately, if you can use the values immediately after calculating them, you can skip the class and just calculate them all in line. You could do this via a loop or calculate them separately using built in functionality.

JAVA Pass by reference error in method

I was trying to perform sorting of integers in an array and it worked fine.
But when i try to modify the program by including a "pass by reference" concept via a method, it is throwing error "cannot find symbol".
I am new to JAVA and learning by my own, Please help me with what I am doing wrong here.
import java.util.*;
import java.io.*;
public class Sort {
public static void main(String[] args) {
Sort obj = new Sort();
Scanner in = new Scanner(System.in);
int i, p, k, arr[];
arr = new int[10];
System.out.println("Enter the numbers for sorting \n");
for (i = 0; i < 5; i++) {
arr[i] = in.nextInt();
}
for (i = 0; i < 5; i++) {
for (p = 0; p < 5; p++) {
if (arr[i] < arr[p]) {
/*
* moving the below block for swapping to a new method. k =
* arr[i]; arr[i]= arr[p]; arr[p]= k;
*/
obj.swap(obj);
}
}
}
System.out.println("\n");
for (i = 0; i < 5; i++)
System.out.println(arr[i]);
}
public void swap(Sort m) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
}
The error I am getting is :
"Sort.java:44: error: cannot find symbol
m.k = m.arr[i];
^
"
Similarly 10 such errors for other variables as well.
You are trying to use index variables (i and p) that don't exist in the context you are trying to use them (inside swap() method body) as well as members of Sort (k and arr) which don't exist. The scope of all these, you have limited to the method body of main():-
public void swap(Sort m) {
m.k = m.arr[i]; //No 'i' in swap(). No 'k' or 'arr' in 'm'(an instance of 'Sort')
m.arr[i] = m.arr[p]; //No 'p' in swap()
m.arr[p] = m.k;
}
Short-term Solution
Change your swap() method to
//Now accepting in i and p
public void swap(Sort m, int i, int p) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
then call it like this
obj.swap(obj, i, p); //pass in i and p
and move your Sort variables to be accessible members of Sort
public class Sort {
public static int k; //now accessible with m.k
public static int[] arr = new int[10]; //now accessible with m.arr
...
}
Lastly, is it intentional that your array is 10 long but you only fill it with 5 numbers?
Pass-by-Reference
There is no "pass-by-reference" in Java. Everything is passed by value. The confusing thing is that what is passed by value is technically a reference to the object, meaning you get strange effects like you can edit the object but not reassign it.
Solution: move the stuff back from the swap method to where it was.
Alternatively, provide the necessary values as parameters to swap.

Java ArrayList<Double> as Parameter

I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.

Categories