I'm trying to retrieve the item at the specified index in an array as shown in the body of the forloop.
public int arrayCount9(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i ++) {
if (Array.get(nums, i) == 9) {
count ++;
}
}
return count;
}
However, the correct code in this problem is actually this:
public int arrayCount9(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i ++) {
if (nums[i] == 9) {
count ++;
}
}
return count;
}
Is there a difference between Array.get(nums, i) == 9) and (nums[i] == 9)? The documentation for get(Object array,int index) seems suitable for this problem. In addition, I've actually never encountered (nums[i] == 9) before so if you could explain that code as well, much appreciated!
As far as I can tell from the documentation, the most important difference between the two is that Array.get(myArray, myIndex) will return a raw Object, whereas myArray[myIndex] will return a value of the type that myArray stores.
For example, if you have an array of Strings named myStringArray, Array.get(myStringArray, 4) will give you a nondescript Object value, whereas myStringArray[4] will give you a String value.
In general, people tend to use the myArray[myIndex] syntax unless they have a compelling reason not to. It essentially means "get the item in the array named myArray at index myIndex."
Related
I'm writing a method in a class that retrieves an array and a set value from main. The aim is to locate the position of that given value and return this to main (if the value does not exist in the array it returns -1).
To my problem: when i run my code Java says: int cannot be converted to boolean. And points me to the if-statement in the code below. I tried switching the "="-sign to a ">=", and then it runs smoothly (but then it doesn't work like it's supposed to...).
Can anyone see why it thinks i want to convert it to a boolean?
public static int containsIntElement(int[] A, int val)
{
int pos = -1;
for (int i = 0; i < 10; i++)
{
if(A[i] = val)
{
pos = i;
}
}
return pos;
}
The correct way to evaluate two ints is ==, not =:
public static int containsIntElement(int[] A, int val)
{
int pos = -1;
for (int i = 0; i < 10; i++)
{
if(A[i] == val) //Note this
{
pos = i;
}
}
return pos;
}
The = operator is for assignments, so in
if(A[i] = val)
You're assigning the value val to the variable A[i], that is not a condition
Please pay attention to minor details
if(A[i] = val) // is incorrect .. in some programming language it is correct. but boy o boy it would make you cry.
if(A[i] == val) // is correct.
You use = (the assignment operator) where you intended to use == (the comparison operator).
What your if does is:
Assign val to A[i] then try (and fail) to make a logical value from A[i]
(naming conventions also say A should be lowercase)
This is more than likely a simple question for someone who is more familiar with Java than I am. Here's the gist of my issue:
I have a function that basically generates the possible combinations of the objects contained within an ArrayList. Being that I have multiple objects that need to use this function, the function is screaming at me to be made generic. The issue I'm encountering, though, is that an enhanced for-loop is unable to resolve method calls from the generic iterator. I understand why this happening, but I'm not familiar enough with Java to know how to resolve this issue. In any case, here is my code:
private <T> ArrayList<T> determineIdealOrderCombination(ArrayList<T> orders, int position){
// Local Variable Declarations
List<ArrayList<T>> subsets = new ArrayList<>();
int k = orders.size()+1; // Add one due to the do-while loop
int theoreticalQuantity;
int indexOfMaxProfit;
double maxProfit;
int[] s; // Here we'll keep indices pointing to elements in input array
double[] profits; // Here we'll keep track of the profit of each combination
// Begin searching for valid combinations
do {
// Setup
k--;
s = new int[k];
profits = new double[k];
// Generate combinations
if ( (k <= orders.size()) && (k > 0) ) {
// Set the first index sequence: 0, 1, 2,...
for (int i = 0; (s[i] = i) < k - 1; i++) ;
subsets.add(getSubset(orders, s));
for (; ; ) {
int i;
// Find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == orders.size() - k + i; i--) ;
if (i < 0) {
break;
} else {
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(orders, s));
}
}
// All combinations have been evaluated, now throw away invalid combinations that violate the upper limit
// and calculate the valid combinations profits.
for (int i = 0; i < subsets.size(); i++) {
// Calculate the final position
theoreticalQuantity = position;
profits[i] = 0;
for (T t : subsets.get(i)) {
theoreticalQuantity += t.getQuantity(); // <-- THE PROBLEM
profits[i] += calculateProjectedProfit(t.getSecurity(), t.getQuantity(), t.getPrice()); // <-- THE PROBLEM
}
if(theoreticalQuantity > _MAX_POSITION_PER_ASSET){
// Negate profits if final position violates the position limit on an asset
profits[i] = Double.MIN_VALUE;
}
}
}
else{
break;
}
}
while( (subsets.size() == 0) );
// Verify that the subset array is not zero - it should never be zero
if(subsets.size() == 0){
return new ArrayList<>();
}
// Return the most profitable combination, if any.
indexOfMaxProfit = -1;
maxProfit = Double.MIN_VALUE;
for(int i = 0; i < profits.length; i++){
if(profits[i] != Double.MIN_VALUE){
if(profits[i] > maxProfit){
maxProfit = profits[i];
indexOfMaxProfit = i;
}
}
}
if( (maxProfit > 0) && (indexOfMaxProfit != -1) ){
return subsets.get(indexOfMaxProfit);
}
else{
return new ArrayList<>();
}
}
Any help would be appreciated.
This is how you tell the compiler that the incoming objects have the relevant methods:
public interface MyCommonInterface {
public int getQuantity();
}
private <T extends MyCommonInterface> ArrayList<T> determineIdealOrderCombination(ArrayList<T> orders, int position) {
As an additional note, i would read some tutorials on generics before attempting to use them. they are a little tricky to get the hang of initially. however, once you put out a little effort to learn the basics, you should be in a much better place to actually utilize them.
The assignment is to create a method that finds the second largest even int in an array of ints. I am restricted from using any methods from any libraries.
Here is my code that works for all cases:
public static int getSecondLargestEven(int[] ary) {
int i;
aryLength = ary.length;
int largestEven = -1;
int secondLargestEven = -1;
for (i = 0; i < aryLength; i++) {
if (ary[i] % 2 == 0) {
if (ary[i] > largestEven) {
if (largestEven != -1)
secondLargestEven = largestEven;
largestEven = ary[i];
} else {
if (ary[i] != largestEven) {
if (secondLargestEven == -1 || ary[i] >= secondLargestEven) {
secondLargestEven = ary[i];
}
}
}
}
}
Prior to calling the methodI require the array to have more than one even else no method call.
So, when secondLargestEven == -1, I know there is a duplicate.
Is there a more efficient (less use of operators, less loops used, less memory allocation) way to accomplish the objective? How can I improve the logic of my code? How can I improve my code overall?
I don't like that I have to assign the magic number -1 to secondLargestEven and largestEven because they are technically named to hold EVENS. Would it be efficient to use a loop to assign a valid even integer in the array to both secondLargestEven and largestEven and THEN proceed to search? Thanks in advance.
You can make the code cleaner by not explicitly checking for the case when the largest and second variables are equal to -1.
Just set these variables to Integer.MIN_VALUE before the loop - this is the same as assuming that there were two additional values in your array that come before all the others, and they both have the value Integer.MIN_VALUE.
public static int secondLargestEven(int[] x) {
int largest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 == 0) {
if (x[i] > largest) {
second = largest;
largest = x[i];
} else if (x[i] > second) {
second = x[i];
}
}
}
return second;
}
Edit -- I thought I'd throw in that you can remove one level of nesting by using a continue statement inside the loop to skip the cases where you have an odd integer, although some people would consider this more difficult to understand than the code above.
It's a tradeoff - you use explicit control flow inside the loop (bad) but you remove a nesting level (good).
public static int secondLargestEven(int[] x) {
int largest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] % 2 != 0)
continue;
if (x[i] > largest) {
second = largest;
largest = x[i];
} else if (x[i] > second)
second = x[i];
}
}
return second;
}
Just a fun thought... in Haskell, this function can be written in one line
import Data.List (sort)
secondLargestEven = (!! 1) . reverse . sort . filter even
or, if you want to be more efficient
import Data.List (sortBy)
import Data.Ord (comparing)
secondLargestEven = (!! 1) . sortBy (comparing negate) . filter even
This is just-for-fun implementation:
public static int secondLargestEven(int[] array) {
Set<Integer> evenSet = new TreeSet<>(Collections.reverseOrder());
for (int n : array) if (n % 2 == 0) evenSet.add(n);
return new ArrayList<>(evenSet).get(1);
}
This method is extremely inefficient (I cant look at it) but returns second largest even number :)
Method works only if array has second largest even number.
public static int findLargestMark(ArrayList<Result> array)
{
int last = 0;
int largestPOS = 0;
for (int i = 1; i <= array.size(); i++)
{
for (Result s : array)
{
int num = s.getMark();
if (num > last)
{
last = num;
largestPOS = i++;
}
}
}
Does anyone have any idea why this isn't returning the position of the largest value?
I'm sorry but I'm a bit of a newbie to Java.
largestPOS = i++;
This is incrementing i which means it skips the next number. If that next number is the biggest, you'll miss it.
Your code won't compile. You need a return statement.
Your outer loop skips the first element because it starts at 1 instead of 0. Arrays and lists are 0 based.
You only need one loop to accomplish this. I'd remove the inner loop since you're trying to return the index and a foreach loop doesn't give you the index.
If your array is empty, it will set largestPOS to 0. That is not correct. Other algorithms in this situation would return -1 to mean "index not found". See String.indexOf for example.
If you want to find the largest mark, no need to reinvent the wheel. Use Collections.max and provide a custom Comparator :
Result r = Collections.max(array, new Comparator<Result>() {
#Override
public int compare(Result o1, Result o2) {
return Integer.compare(o1.getMark(), o2.getMark());
}
});
Then if you really want to find the position of this object in the list you can use indexOf :
array.indexOf(r);
Note that will return the index of the first occurrence of the specified element in the list.
If you want to get the index of the last occurrence, you can use :
array.lastIndexOf(r);
There are several reasons to this program's failure:
You need to check that your array has at least one item
You need to start the last at the initial mark, not at zero
You need to loop from one, inclusive, to array.size(), exclusive
You do not need a nested loop
You need to add a return statement
Here is how you can fix your code:
public static int findLargestMark(ArrayList<Result> array) {
if (array.size() == 0) return -1; //
int last = array.get(0).getMark();
int largestPOS = 0;
for (int i = 1; i < array.size(); i++) {
int num = array.get(i).getMark();
if (num > last) {
last = num;
largestPOS = i;
}
}
return largestPOS;
}
Because you're iterating through the same array using two nested loops. Keep it simple. Iterate only once through the entire array and find the maximum value and its index.
Try this..
public static int findLargestMark(ArrayList<Result> array)
{
int last = array.get(0).getMark();
int largestPOS = 0;
for (int i = 1; i <= array.size(); i++)
{
Result s = array.get(i);
int num = s.getMark();
if (num > last)
{
last = num;
largestPOS = i;
}
}
return largestPOS;
}
Your code even not compile, java is 0 index based. you should have received a ArrayIndexOfBoundException. However, i would just use Collections.max(array, Comparator):
Result x = Collections.max(array, new Comparator<Result>(){
#Override
public int compare(Result o1, Result o2) {
return Integer.compare(o1.getMark(), o2.getMark());
}
});
And then the index by array.indexOf(x) function, where array is an instance of type ArrayList<Result>
public class ArrayPrac {
public static void main(String[] args) {
int[] arrayOne = {2, 3, 4, 5, 6};
System.out.println(findMin(arrayOne));
}
public static void findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++);
if(list[i] < minValue) {
minValue = list[i];
}
}
}
In the System.out.print part in line 6 it wont run and gives me the compiler error:
The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I seem to have searched for an answer all day, so now I post my specific case.
Cheers.
Fix this, at the end of your findMin() method you must return the minimum value that was found:
return minValue;
And consequently, the method signature must be changed, too:
public static int findMin(int[] list)
It makes sense: if the findMin() method does all that hard work to find the minimum value, the end result must not be left as a local variable, it won't be useful outside if you don't return it after the method invocation ends.
There's another hard-to-find bug lurking, by the way. Remove the ; at the end of the line with the for, and put the contents of the loop inside a pair of {}. Currently, the loop is empty, and the lines after the for lie outside the loop. And the loop condition is wrong, too! here's how the method should look after all the problems are fixed:
public static int findMin(int[] list) {
int minValue = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < minValue) {
minValue = list[i];
}
}
return minValue;
}
System.out.println takes a String input but you are passing a void. As your method findMin returns void. This is causing the compiler error.
Now speaking about the logical problem, you may want to display the output of findMin method but the method does not return anything. So returning minValue may make sense here.
Once you return the int value from minValue method then you can display the result by concatenating it to a an empty string. Something like this:
System.out.println("" + findMin(arrayOne));
The method findMin() is declared as returning type void: Either declare it to return something (and return something),
public static int findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++)
if(list[i] < minValue) {
minValue = list[i];
}
return minValue;
}
Note fixing bug: removing semicolon from after for()