Below is a method that takes in studentarray and the topStudentIndexof a value calculated by another method previous.
I have multiple objects in my array. However, the for loop only managed to loop through once, and it returned the first value straight away.
I have no clue why the for loop stopped even though my st.lengthis more than
public static int computeNextHighestOverallStudentIndex(Student[] st, int topStudentIndex) {
double nextHighestOverall= 0;
int nextHighestStudentIndex = 0;
for (int i = 0; i < st.length; i++) {
if ((st[i] != null) && (!(i == topStudentIndex))){
double studentOverall = st[nextHighestStudentIndex ].getOverall();
if (studentOverall > nextHighestOverall) {
nextHighestOverall= studentOverall;
nextHighestStudentIndex = i;
}
}
}
return nextHighestStudentIndex ;
}
It looks like
double studentOverall = st[nextHighestStudentIndex ].getOverall();
should be
double studentOverall = st[i].getOverall();
since you want to check all the Students in the array and not just the first one (st[nextHighestStudentIndex ] will always return the first Student, since you initialize nextHighestStudentIndex to 0).
You want to traverse the entire array using st[i] (not st[nextHighestStudentIndex])
Related
I'm not really sure how to word the question for the title but this post explains what I'm after. I apologize if my question is worded incorrectly.
In Java, how would I go about creating a method that returns the number of 'hippos' found in two different integer arrays:
int[] hippo1 = new int[100];
int[] hippo2 = new int[10000];
given that a 'hippo' is considered an integer that is 75 or above?
Would it be?
public static int calcNumberOfHippos(int[] hippos)
{
for (int i = 0; i < hippos.length; i++)
{
if (hippos[i] >= 75)
{
return hippos[i];
}
}
int numHippos = (int)hippos.length;
return numHippos;
}
I'm not sure if I should return hippos.length at the end. That's the only way I can get it to return something. I would really like to return hippos[i] but every time I try to return that out of the for loop it says that it doesn't recognize the variable i. It says Cannot find symbol variable i.
public static int calcNumberOfHippos(int[] hippos)
{
for (int i = 0; i < hippos.length; i++)
{
if (hippos[i] >= 75)
{
return hippos[i];
}
}
return hippos[i];
}
Can anyone please point me in the right direction?
If you want to calculate the number of hippos (how many members of the array are larger than 75), then this code could help:
public static int calcNumberOfHippos(int[] hippos) {
int numOfHippos = 0;
for (int i = 0; i < hippos.length; i++) {
if (hippos[i] >= 75)
{
numOfHippos++;
}
}
return numOfHippos;
}
The idea is to go over the array and count up every time a hippo is spotted. You don't need to return the first hippo that you see - which is what your original code would've done.
int hippoCount = Arrays.stream(hippos).reduce(0, (acc, n) -> acc + (n >= 75 ? 1 : 0));
should do the trick.
This program takes integers from user input and puts them in a collection. It then prints the positive values first, then the negative values, and doesn't print repeated numbers. It stops asking for input once the user enters 0. Here is the code:
public class Intcoll2
{
private int[] c;
private int[] d;
private int howmany = 0;
public Intcoll2()
{
c = new int[500];
}
public Intcoll2(int i)
{
c = new int[i]
}
public void insert(int i)
{
if (i > 0)
{
int j = 0;
while ((j <= howmany) && (c[j] != i)) j++;
if (j == howmany)
{
if (j == c.length - 1)
{
d = new int[2*c.length];
for (int k = 0; k<c.length; i++){
d[k] = c[k];
}
c = d;
}
c[j] = i; c[j + 1] = 0;
}
howmany++;
}
}
public int get_howmany()
{
int j=0, howmany=0;
while (c[j]!=0) {howmany++; j++;}
return howmany;
}
Now my current print method looks like this:
public void print()
{
int j = 0;
System.out.println();
while (j <= howmany)
{
System.out.println(c[j]); j++;
}
}
But when I try to use that in my client, it only prints out zeros. Any help with what I'm doing wrong would be greatly appreciated.
An answer that you were probably not looking for, but still on the only real answer you should care about.
Your problem is not that somewhere in that code a bug is hiding. The problem is that your code is confusing beyond limits:
Dont use single-character variable names.
The constructor that takes an int ... creates an empty array!
Dont say "collection" when you are using arrays.
Dont give fields and local variables the same name.
Seriously: understanding this mess is mainly complicated and hard because you wrote code that is hard to read.
Now you are asking other people to debug such complicated code that you (the author who created it!) do not understand in the first place.
Instead, you might throw this whole thing away. And slowly write it again; but in a way that isn't at all confusing to the reader.
I took a look at your class and rewrote it in a more legible manner. I didn't test it but I'm confident it works. You can check it out and hopefully understand what's happening. Hope this helps!
public class IntCollection2 {
private int[] collection; // A large allocation, not neccessarily filled up.
private int currentSize; // The number of spots currently filled in the collection.
public IntCollection2() {
collection = new int[500];
currentSize = 0;
}
public IntCollection2(int size) {
collection = new int[size];
currentSize = 0;
}
/**
* Inserts a new element into the internal array. If the current array is filled up,
* a new array double the size of the current one is allocated.
* #param element An int to insert into the collection. Must not be '0'.
* #return True if the element was successfully inserted, false if the element was
* equal to '0' and was ignored.
*/
public boolean insert(int element) {
if (element != 0) {
if (currentSize < collection.length - 1) {
collection[currentSize] = element;
} else {
int[] newCollection = new int[collection.length * 2];
for (int i = 0; i < currentSize; i++) {
newCollection[i] = collection[i];
}
newCollection[currentSize] = element;
collection = newCollection;
}
currentSize++;
return true;
} else {
return false;
}
}
/**
* Not actually necessary because the class automatically updates its currentSize
* every time a new element is inserted.
* #return The current number of filled spots in the internal array.
*/
public int getCurrentSize() {
int size = 0;
for (int i = 0; i < collection.length && collection[i] != 0; i++) {
size++;
}
return size;
}
/**
* Prints out all the elements currently in the collection, one on each line.
*/
public void print() {
System.out.println();
for (int i = 0; i < currentSize; i++) {
System.out.println(collection[i]);
}
}
}
FYI: this class just prints out every element in the collection, in order. You mentioned something about printing positive then negative values, but I leave that to you.
EDIT: I'm guessing you're brand new to programming, so I just want to clarify exactly what a collection is. An array is an ordered list of elements. When you create an array, the computer sets aside a bit of memory to hold exactly the number of elements you told it to. You cannot change the size of an existing array. A collection is basically a wrapper around an array. It makes a bigger array than it needs to hold its elements, and when its array becomes full, it allocates a new, bigger one that can hold more elements.
As the title reads, I have been thinking about creating multiple nested loops that aim to achieve one purpose. Move two generated random numbers between 0-9 through each possible possition of an array.
For example, App generates first number (fNum) 1 and second number (sNum) 6. It then moves these numbers in the array which containts ABC. However firstNum and secondNum will need to also try all the possible combinations, so each one will need to be different with each loop.
-1ABC6
-A1BC6
-AB1C6
-ABC16
-ABC61
-AB6C1
-A6BC1
-6ABC1
-A6B1C
-A61BC
-A16BC
-A1B6C
-A1BC6
and so on...
I beleive the best way will be to create a method for generating a counter, which increments the numbers which I can call.
private int getNextNumber(int num) {
if (num == 0) {
return num;
} else {
num++;
}
if (num < 10) {
return num;
} else {
return -1;
}
}
Then I will need multiple nested loops... I have decided to go for several loops which will go infinitly.
while (j < maxlen) {
//J = 0 and maxlen = length of text so in this case 3 as it is ABC
//Add two numbers and check against answer
while (fNum != -1 || sNum != -1) {
//incrememnt numbers
fNum = getNextNumber(fNum);
System.out.println(fNum);
sNum = getNextNumber(sNum);
System.out.println(fNum);
}
String textIni = "ABC";
int lenOfText = textIni.length();
char[] split = textIni.toCharArray();
for (int i = 0; i < lenOfText; i++) {
//here it will look at the length of the Text and
//try the possible positions it could be at....
//maybe wiser to do a longer loop but I am not too sure
}
}
Since you don't need to store all possible combinations, we will save some memory using only O(n) storage with an iterative solution. I propose you a basic implementation but don't expect to use it on large arrays since it has a O(n³) complexity.
public static void generateCombinationsIterative(List<Integer> original, int fnum, int snum) {
int size = original.size();
for (int i=0 ; i<=size ; i++) {
List<Integer> tmp = new ArrayList<>(original);
tmp.add(i,fnum);
for (int j=0 ; j<=size + 1 ; j++) {
tmp.add(j,snum);
System.out.print(tmp + (i == size && j == size + 1 ? "" : ", "));
tmp.remove(j);
}
}
}
For your culture, here is an example of a recursive solution, which takes a lot of memory so don't use it if you don't need to generate the lists of results. Nevertheless, this is a more general solution that can deal with any number of elements to insert.
public static List<List<Integer>> generateCombinations(List<Integer> original, Deque<Integer> toAdd) {
if (toAdd.isEmpty()) {
List<List<Integer>> res = new ArrayList<>();
res.add(original);
return res;
}
int element = toAdd.pop();
List<List<Integer>> res = new LinkedList<>();
for (int i=0 ; i<=original.size() ; i++)
// you must make a copy of toAdd, otherwise each recursive call will perform
// a pop() on it and the result will be wrong
res.addAll(generateCombinations(insertAt(original,element,i),new LinkedList<>(toAdd)));
return res;
}
// a helper function for a clear code
public static List<Integer> insertAt(List<Integer> input, int element, int index) {
List<Integer> result = new ArrayList<>(input);
result.add(index,element);
return result;
}
Note that I did not use any array in order to benefit from dynamic data structures, however you can call the methods like this :
int[] arr = { 1,2,3 };
int fnum = 4, snum = 5;
generateCombinationsIterative(Arrays.asList(arr),fnum,snum);
generateCombinations(Arrays.asList(arr),new LinkedList<>(Arrays.asList(fnum,snum));
Note that both methods generate the combinations in the same order.
First off, my program is not compiling. Any ideas? I have no idea why and my Eclipse program isn't working...
Also, how do I get my "isLucky" method to loop through my array?
And did I print out my results correctly in the main method?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
System.out.println(sum(a))
else
result = sumOfEvens(a);
System.out.println(sumOfEvens(a))
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false;
}
// write the static methods isLucky, sum, and sumOfEvens
}
Your compiler error, 'else' without 'if' is because you have something like this:
if(isOkay)
doSomething();
andThenDoSomethingElse();
else
doAnotherThing();
andEvenSomethingElse();
And you must put each block in curly braces, like this:
if(isOkay) {
doSomething();
andThenDoSomethingElse();
} else {
doAnotherThing();
andEvenSomethingElse();
}
I strongly recommend using curly braces in all ifs (and whiles and fors and everything else), even when there's only a single statement.
More information can be found at this question: Else without if
Honestly there is no regulation that says we have to use code blocks. Syntax typically says that after we read the if we are looking for only one statement if your condition contains multiple statements then we do have to block that code up, another thing is try to keep that indentation whenever you enter methods conditions and then statements. Id love to write the easy route to get the output you desire. Think about this why are you sending these methods arrays? What is stopping you from simply looping in your main method and passing each iteration to these methods sum lucky, even...Your variables should usually be initialized at top or at the beginning of a method to have those around the life of a methods execution.Below is clearly not compile ready code, however this will edge you in the right place to understand this problem more than use brackets.
boolean isLucky;
int[] IntegerArray;
Scanner scan;
//Final for constant values Typically these would be in all uppercase to indicate to
//other that this is a final anywhere
//in this class those will stick out.
final int luckyOne = 7;
final int luckyTwo = 13;
final int luckyThree = 18;
for(int i=0;i<IntegerArray.length;i++){
//snag me Boolean value for this number
isLucky();
if(isLucky)//example of completely legal if statement adding a system.out statement
//means yes i have to block this
sum(i);
else
even(i);
}
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>