Method to get the sum of an ArrayList - java

I am getting the totals of various String ArrayLists such as [1,3,4]...
by parsing them into integers and getting the total. This worked when I coded each individual one, but when I made a method by passing in the total int value and arraylist I always get a value of zero.
A method would save a lot of time.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
vigoroustotal(list,Vigor);
public static void Listtotal(String par, int tt) {
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
}

Any changes you do to tt inside your method won't be visible anywhere else, because Java passes everything by value. Make the method return an int instead.

Your mistake her is passing the function tt and expecting it to be modified. Java doesn't modify parameters passed to functions. The corrected code would be this:
public static int ListTotal(List<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
and would be used like this:
Vigor = ListTotal(list);

The changes that are made to the integer tt in the Listtotal() method will not be visible anywhere else but that method. You can make that method return an integer to solve that!
public static int Listtotal(ArrayList<String> par) {
int tt = 0;
for (String s : par) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
And then you need to change the main method:
public static void main(String[] args) {
list = new ArrayList<String>();
Vigor = Listtotal(list);
}

As, said, you need to return the total since java passes everything by-value, so the int tt you pass in won't hold a reference to the Vigor variable outside the method.
Therefore, when you pass in primitive types such as (int, char, boolean, byte etc.), anything you do to them inside a method won't be visible outside the method.
However, when you pass in a reference type (Objects such as ArrayList), it is still passed-by-value but that value is a copy of the reference to the Object outside the method. So, in the populateList method bellow, I can just call ArrayList.add() on the input because this input, even though it is passed-by-value, still points to the original Object that was put into this method.
public class Playing {
static ArrayList<String> list;
static int Vigor;
public static void main(String[] args) {
list = new ArrayList<String>();
populateList(list);
Vigor = getListTotal(list);
System.out.println("Total is:\t" + Vigor);
}
public static void populateList(ArrayList<String> list) {
String[] sampleData = { "4", "7", "2" };
for(int i = 0; i < sampleData.length; i++) {
list.add(sampleData[i]);
}
}
public static int getListTotal(ArrayList<String> list) {
int tt = 0;
for (String s : list) {
int i = Integer.parseInt(s);
tt += i;
}
return tt;
}
}

What you want is the... let's call it CountingList,
public class CountingList {
private List<Integer> integers = new ArrayList<Integer>();
private int sum;
public add(String s) {
int value = Integer.parseInt(s);
integers.add(value);
sum += value;
}
private void updateSum() {
sum = 0;
for (int i : integers) {
sum += i;
}
}
}
Obviously, you'll want to expose the functionality you need to use outside of the class, but this is (one) way of encapsulating the behavior you're needing.

Related

Is it possible to modify the value of an attribute sent in argument of a function in Java?

I'm working on a calculator and I search how I can optimize my code.
The thing is that I have much code duplication due to if I'm working on the first number of the calculation or the second. So I'm searching if it is possible to modify the value of an attribute sent in argument of a function ? (I think not because I saw nowhere the answer).
Maybe I'm expressing myself badly so here is a code below to explain what I'm talking about:
public class MyClass
{
private static int number1 = 1;
private static int number2 = 2;
public MyClass()
{
changeValueOf(number1, 3);
}
private static void changeValueOf(int number, int value)
{
//Change here the value of the correct field
}
}
First of all, you can modify static variables inside the method:
private static void changeValueOf(int value)
{
number1 = value;
}
But I guess that is not what you a looking for :)
In Java (and in most other languages) primitive data type (int, short, long, etc) passed by value, e.g. the copy of value passes to the method (function).
And reference types (objects, e.g. created with new operator) passed by reference. So, when you modigy the value of reference type (object) you can see the changes in the outer scopes (for example, in method caller).
So, the answer is no - you cannot change the value of int so that the outer scope would see the updated value.
Howewer, you could wrap your int values with some object - and it change the value inside of it:
public class Example {
public static void main(String[] args) {
Example app = new Example();
// Could be static as well
Holder val1 = new Holder(1);
Holder val2 = new Holder(2);
app.changeValue(val1, 7);
System.out.println(val1.value); // 7
}
public void changeValue(Holder holder, int newValue) {
holder.value = newValue;
}
static class Holder {
int value;
Holder(int value) {
this.value = value;
}
}
}
Also, you could create an array with 2 values and update them inside the method, but it's not very good approach IMO
And finally, you could just return updated value and assign it to your variables:
public class Example {
private static int number1 = 2;
private static int number2 = 3;
public static void main(String[] args) {
Example app = new Example();
number1 = app.mul(number1, 7);
number2 = app.mul(number2, 7);
System.out.println(number1); // 14
System.out.println(number2); // 21
}
public int mul(int a, int b) {
return a * b;
}
}
One possibility is to use an array to store your variables, instead of separate variables with numbers affixed. Then you would write number[1] instead of number1 for example. You can pass the array index number around to indicate which variable you are referring to.
public class MyClass
{
private static int[] variables = {1, 2};
public MyClass()
{
// change value of first variable
changeValueOf(0, 3);
// now variable[0] = 3
}
private static void changeValueOf(int number, int value)
{
variables[number] = value;
}
}

Array Method issue

having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
}
}
return arrayX;
}
}
you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress
import java.util.*;
public class Help
{
public static void main(String[] args)
{
ArrayList<Integer> arraysA = new ArrayList<Integer>();
arraysA.add(Integer.valueOf(2));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(19));
arraysA.add(Integer.valueOf(32));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(18));
arraysA.add(Integer.valueOf(25));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(3));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
int varB=8;
newSmallerArray(arraysA,varB);
for(Integer i:arraysA)
{
System.out.println(i);
}
}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
for(int i=0;i<arraysA.size();++i)
{
if(Integer.valueOf(arraysA.get(i))==varB)
{
arraysA.remove(i);
}
}
}
}
Try this code it will not require for loop:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);

How would I utilize a value returned from a method and implement it the main method in java?

Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}

issue with Arrays.asList()

I have a very simple program and I just need to check an array for a value in it.
I have a class called bulkBean. this is it.
public class bulkBean {
private int installmentNo;
private double amount;
public int getInstallmentNo() {
return installmentNo;
}
public void setInstallmentNo(int installmentNo) {
this.installmentNo = installmentNo;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
Now I have an array of this bulkBean type in my program, this is my program.
import java.util.Arrays;
public class test {
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
}
for(int j = 0; j< arr.length ;j++){
System.out.println("INFO: array "+j+" = "+arr[j]);
}
if (Arrays.asList(arr).contains(i) == true) {
return true;
} else {
return false;
}
}
public static void main(String[] arg){
bulkBean bb1 = new bulkBean();
bb1.setInstallmentNo(1);
bb1.setAmount(5500);
bulkBean bb2 = new bulkBean();
bb2.setInstallmentNo(2);
bb2.setAmount(4520);
bulkBean[] bulkArray = new bulkBean[2];
bulkArray[0] = bb1;
bulkArray[1] = bb2;
boolean a = scan_bulkList(bulkArray,1);
System.out.println("val = "+a);
}
}
I create 2 instances of bulk bean and I set values to them. Then I added those two instances to an array. Then I pass that array to the method to check for a value(also given as a parameter. In this case it is 1.). If the array contains that value, it should return true, otherwise false.
whatever value I enter, it return false.
Why do I get this issue?
Arrays.asList() returns a List which has a single element - an array. So, you are actually comparing against an array. You need to compare against each value in the array.
As TheListMind told, Arrays.asList() taken on an int[] gives you a list containing the array.
Personally, I would construct directly the List instead of constructing the array, or even better (no need of array instanciation), test while iterating the bulk array :
for(int x=0;x<bulkList.length;x++){
if (bulkList[x].getInstallmentNo() == i){
return true;
}
}
return false;
The mistake you made here is , you created the int array which must be Integer array because Arrays.asList().contains(Object o); makes the input parameter also Integer(Integer i). int is not an object Integer is the object. Hope it will work.
int[] arr = new int[bulkList.length];
change to:
Integer[] arr = new Integer[bulkList.length];
Change the method as below to avoid complications:
public static boolean scan_bulkList(bulkBean[] bulkList, int i) {
int[] arr = new int[bulkList.length];
for(int x=0;x<bulkList.length;x++){
arr[x] = bulkList[x].getInstallmentNo();
if (bulkList[x].getInstallmentNo()==i) {
return true;
}
}
return false;
}

Array of queues not compiling - cannot find symbol error

I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable

Categories