Sum of ArrayList in a method - java

I'm new to coding. My task is to get a total duration of all tracks in a playlist (in seconds). There is an accessor method called getDur in another class. There is also toString method that converts everything into seconds. This is my code.
private ArrayList<Track> tracksN;
public int getDurTotal()
{
for (Track b: tracksN)
{
int sum = 0;
for (int i=0; i<tracksN.size();i++)
{
sum += tracks.get(getDur(i));
}
}
return sum;
}
However, I'm getting an error message that says "method getDur in class PlayList cannot be applied to given type. Required: no arguments; Found: int; reason: actual and formal argument lists differ in length".

Your code is iterating over the track list twice. One of the for loops needs to go. Either:
int sum = 0;
for (int i = 0; i < tracksN.size(); i++) {
Track track = tracksN.get(i);
sum += track.getDur();
}
Or
int sum = 0;
for (Track track : tracksN) {
sum += track.getDur();
}
Between these two approaches, the second approach is better as it will work correctly (with good performance) with all List<> types, not just with ArrayList<>. It's also simpler.

You need to get the track from the list, then call getDur on that. Try this:
private ArrayList<Track> tracksN;
public int getDurTotal()
{
for (Track b: tracksN)
{
int sum = 0;
for (int i=0; i<tracksN.size();i++)
{
sum += getDur(tracks.get(i));
}
}
return sum;
}

You just want to use one for loop
int sum = 0;
for (Track track : tracksN)
{
sum += track.getDur();
}
return sum;

The answer to that is in the error itself; read it again. PlayList cannot be applied to given type. Required: no arguments
Meaning you called getDur(i) with argument i.
But if you can scroll through your code and find the method getDur doesn't need any parameter.
I bet it just looks something like getDur(){ or something and it's return type I assume is int.
So if you can show the code for you class PlayList maybe someone can help you implement you code properly.

Related

Elegant way to find min of an array using method parameters?

I'm looking for an elegant way to express this pseudo code. For my assignment, I cannot change the method signature or parameter type.
private static int smallest(int... nums)
{
return Arrays.stream(nums).min().getAsInt();
}
All I'm trying to do is take a huge varying list of ints as a parameter from the method call and return the smallest int of all the int parameters. I've tried to google and read the API to find out how to correctly implement this, but I've gotten only this far. Can someone help me syntactically correct this to compile and output correctly?
I cannot correctly post my console errors with formatting, so I'm posting it as an update to my OP. To answer #Marvin I'm getting this error in my compiler...
Methods1.java:25: error: cannot find symbol
int small = Arrays.stream(nums).min().getAsInt();
^
symbol: variable Arrays
location: class Methods1
1 error
You almost had it, it's getAsInt() instead of get():
private static int smallest(int... nums) {
return Arrays.stream(nums).min().getAsInt();
}
Complete working sample on ideone.com:
import java.util.Arrays;
class Ideone {
public static void main (String[] args) {
int[] nums = new int[] { 7, -2, 5, 12 };
System.out.println(smallest(nums));
}
private static int smallest(int... nums) {
return Arrays.stream(nums).min().getAsInt();
}
}
Prints:
-2
You could iterate over the whole array like this
private static int smallest(int[] array)
{
//check if the array is empty
if(array.length == 0)
{
//handle, whatever happens if the array is empty
return -1; //maybe you should throw an exception here
}
//storing the smallest found value, start with the first int in the array
int smallest = array[0];
//the iteration
for(int i : array)
{
//check if the current checked value is smaller than the smallest found...
if(i < smallest)
{
//...and if it is, set it as the smallest found value
smallest = i;
}
}
//finally, return the smallest value
return smallest;
}
This should solve your current problem, but in most cases i'd rather recommend to use a pre sorted array or list instead. If the data in it is already stored in ascending order, the first element would always be the lowest and the last element always the highest value.
This method takes an infinite unknown variable quantity of parameters by using varargs as it's argument. Combining all the parameters added from it's call from main into an array of the same type. This was designed to account for mutability of the original method call in main. Finally, returning the smallest integer of all the parameters.
I'm a fairly new programmer, second year into computer science, and I'm not sure if this is even useful for anyone, but I hope it helps. Thanks to everyone here for your awesome tips and error catches. My issue was I forgot to import my Array class and one of my method calls from stream class was incorrectly named.
Lastly, for any veteran programmers out there, aside from this looking snappy and elegant, does this statement execute any faster than doing a simple foreach loop and comparing the num to the last smallest one?
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
// Enter as many as you want here, can be more or less than three
int num1 = 23;
int num2 = 89;
int num3 = 9;
// Apply each variable as an argument for the method call
int smallestNumber = smallest(num1, num2, num3);
// Print out variable value to prove it works
System.out.print(smallestNumber);
}
private static Integer smallest(int... nums)
{
// Found an elegant way to do the stubbed out block of code
// I left the code down there to show what is going on here
try
{
return Arrays.stream(nums).min().getAsInt();
}
catch (Exception e)
{
return null;
}
// The above code is essentially doing the below code
/*try
{
// Initialize Variable to start of array
int smallest = nums[0];
// For:Each Loop: go through each parameter and assign it a local variable to compare with
for(int i : nums)
{
// compare if smaller
if(i < smallest)
{
// If true, set as smallest
smallest = i;
}
}
return smallest;
}
catch (Exception e)
{
return null;
}*/
}
}

Methods with multiple arguments iterating an array

I have this method here:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota) {
boolean aprovaAluno = false;
for(int i = 0; i < materia.length; i++) {
materia[i] = codigoAluno;
for(int j = 0; j < materia[i].length; j++) {
materia[i][j] = codigoMateria;
for(int k =0; k < materia[i][j].length; k++) {
materia[i][j][k] = nota;
if(materia[i][j][k] > 7.0) {
aprovaAluno = true;
}
}
}
}
return aprovaAluno;
}
I'm supposed to call it giving three arguments, #1 student code, #2 subject code and #3 grade. I had declared them as "double" in the method, but Eclipse highlighted it as "cannot convert from double[] to double", so it suggested me to change from this:
boolean exibirAprovacao(double codigoAluno, double codigoMateria, double nota)
To this:
boolean exibirAprovacao(double[][] codigoAluno, double[] codigoMateria, double nota)
And now Eclipse gives me an error when I'm calling my method:
aluno01.exibirAprovacao(codigoAluno, codigoMateria, nota);
Stating that
the method arguments are not applicable to the ones I'm passing
This is my array declaration:
double[][][] materia = new double[3][1][1];
This is an assignment that I have (starting Java + OO now). Any feedback is really appreciated.
First, you must review the logic of your program: If the method is supposed to find out if a certain student of a certain grade has aproved a certain subject, it should search one single value into the materia multi-array. I insist: It must search for a value, not fill in the data.
Second: Based upon the same assumption, to perform such a search, it would be enough if the method received three single parameters.
If Eclipse suggest you to change any method's firm, first understand what is the cause of the error. And do not accept suggestions without being aware of the implications (In this case, I'm afraid you shouldn't have accepted).

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

Find and print the product of all the entries in array

Okay I have tried to write a simple Java code in BlueJ, that finds and prints the product of all the entries in data such as if data is {1,2,3,4} then the result will be 24.
And my code is below:
public class Product {
public static int[] product(int[] a) {
int [] s = new int[a.length];
for (int i =0; i< a.length; i++)
s[i] = a[i]*a[i];
return s; //the definition of your method...
}
public static void main(String[] args) {
//calling the method to seek if compiles
int[] results = Product.product(new int[] { 1,2,3,4 });
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
The above code is giving me the square of each number, which is not what I want to have, somehow I have modify the code that the result will be 24 but I couldn't figure it out, anyone knows how to do it?
First of all, if you are first writing Java it is important to know that variable, function and class names are quite important. Please note that having Product.product() is not a good idea, since the function name is almost the same as the class name. Anyway, regarding your code. Your code is indeed returning the square of your input, what you would want is the following:
public class Product {
public static int getProduct(int[] input) {
int total = 1;
for (int v : input) {
total *= v;
}
return total;
}
}
This will return an integer value with the product of your input array. This also uses a for-each loop instead of a regular for-loop for readability. Also you don't need the index in this case. Good luck with it!
First, your product method needs to return an int rather than an int [].
You need to maintain the product as a variable. You can set it to 1 initially, and then multiply it by each element of the a array in turn; then you just return this value.

Having trouble understanding how to maintain state using classes

I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.

Categories