okay so I am attempting to create a dice game where args[0] is the amount of times the game is played. the game.... two dice are rolled and if the sum does not equal 7 their value is added to a sum. If the sum equals 7 the game is over. I want to keep track of the largest sum out of all the games and the smallest which should be zero always because when the sum equals 7 it sets the sum to 0.
Here is my code. I don't think what it is printing is what I am going for...help?Also how do i auto format in eclipse?
public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count=0;
int theSum=0;
int lowest=500;
int finalSum=0;
int diceSum=0;
while (count !=Integer.parseInt(args[0])){
count=count+1;
theSum=0;
while(diceSum!=7){
diceSum=0;
dice1=1 + (int)(Math.random() * ((6 - 1) + 1));
dice2=1 + (int )(Math.random() * ((6 - 1) + 1));
diceSum=dice1+dice2;
if (diceSum !=7){
theSum=theSum+diceSum;
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}
}
}
}
System.out.println("After "+args[0]+" simulations: ");
System.out.println("Biggest sum: "+finalSum);
System.out.println("Smallest sum: "+lowest);
}
}
I fixed it
public class diceGame {
public static void main(String[] args) {
int dice1;
int dice2;
int count = 0;
int theSum = 0;
int lowest = Integer.MAX_VALUE;
int finalSum = 0;
int diceSum;
int totalSum=0;
while (count < Integer.parseInt(args[0])) {
count = count + 1;
diceSum=0;
theSum=0;
while (diceSum!=7) {
diceSum = 0;
dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
diceSum = dice1 + dice2;
if (diceSum != 7) {
theSum = theSum + diceSum;
}
//System.out.println("the sum is "+theSum);
}
if (theSum > finalSum) {
finalSum = theSum;
}
if (theSum < lowest) {
lowest = theSum;
}
totalSum=totalSum+theSum;
}
double average=(double)totalSum/(Double.parseDouble(args[0]));
System.out.println("After " + args[0] + " simulations: ");
System.out.println("Biggest sum: " + finalSum);
System.out.println("Smallest sum: " + lowest);
System.out.println("The average is: "+average);
}
}
It is because the lowest value of 2 dice when added is 2, not 0. And if you roll a 7 on the first roll, then you will not update your biggest and lowest. You need to move those checks outside the loop.
while(diceSum!=7){
diceSum=0;
dice1=1 + (int)(Math.random() * ((6 - 1) + 1));
dice2=1 + (int )(Math.random() * ((6 - 1) + 1));
diceSum=dice1+dice2;
if (diceSum !=7) {
theSum=theSum+diceSum;
}
}
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}
If diceSum is seven, your check for min/max is not executed because you put it into braces of if(diceSum!=7). So if diceSum is seven, the mininum is not updated.
Also the lowest sum is not always 0. For example:
First diceroll:
Dice1: Value 5
Dice2: Value 3
Which makes a diceSum=8.
So it's not equal 7, so theSum becomes 0+8=8
Because 8>0 (theSum>finalSum) finalSum gets updated: finalSum=8;
Because 8<500 (theSum<lowest) lowest gets updated: lowest=8;
Next dice roll
Dice1: Value 4
Dice2: Value 3
diceSum=7
Even if you corret your braces like
while (count !=Integer.parseInt(args[0])){
count=count+1;
theSum=0;
while(diceSum!=7){
diceSum=0;
//Corrected Random Brace (see comment below your question)
dice1=1 + (int)((Math.random() * (6 - 1)) + 1);
dice2=1 + (int)((Math.random() * (6 - 1)) + 1);
diceSum=dice1+dice2;
if (diceSum !=7){
theSum=theSum+diceSum;
} // CHANGED BRACE POSITION HERE
if (theSum>finalSum){
finalSum=theSum;
}
if (theSum<lowest){
lowest=theSum;
}
}
}
lowest will still be set to 8. Not to zero. The lowest will only be zero, if a game round exist where the dice sum is 7 in the FIRST dice roll.
Related
I'm making a game for an extra assignment for my college and I have to create a dice game known as "balut" I'm having some issues with assigning values to an array, and having the dice values stored within this array.
I'm in week 9 of 11 of my course we've covered arrays and methods however this is a new concept for me. The goal is as follows:
Balut = all five dice have the same number.
Straight = a total of 15 Or 20.
Sixes = 1 or more sixes.
Fives = 1 or more fives.
Fours = 1 or more fours.
10 rounds.
Total scoring of categories.
total of scores.
If no category is met "none" is printed.
I've put at least 14 hours into this and it was intended to be a 6 to 8 hour program and I still am struggling, questioning if I have the intelligence for the course and am hoping someone here can explain what I'm doing wrong or even what I should be studying.
I've tried creating a single array and assigning all dice values to this array, I run into the problem of when it comes to comparing the values I don't know how to do dice 1 == dice 2 == dice 3 etc.
I've then attempted to make 5 arrays 1 for each dice and use the compare array method which again I can only seem to get it to compare 2 arrays or variables I can't get it to compare all 5 like I'm attempting.
public static void main(String[] args) {
int[] Dicearraytotal1 = new int[10];
int[] Dicearraytotal2 = new int[10];
int[] Dicearraytotal3 = new int[10];
int[] Dicearraytotal4 = new int[10];
int[] Dicearraytotal5 = new int[10];
for (int i = 0; i < Dicearraytotal1.length; i++) {
Integer dice1 = (int) (Math.random() * 6 + 1);
Integer dice1val = dice1;
Integer dice2 = (int) (Math.random() * 6 + 1);
Integer dice2val = dice2;
Integer dice3 = (int) (Math.random() * 6 + 1);
Integer dice3val = dice3;
Integer dice4 = (int) (Math.random() * 6 + 1);
Integer dice4val = dice4;
Integer dice5 = (int) (Math.random() * 6 + 1);
Integer dice5val = dice5;
Dicearraytotal1[i] = (dice1val);
Dicearraytotal2[i] = (dice2val);
Dicearraytotal3[i] = (dice3val);
Dicearraytotal4[i] = (dice4val);
Dicearraytotal5[i] = (dice5val);
Integer total = (dice1val+dice2val+dice3val+dice4val+dice5val);
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(Dicearraytotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(Dicearraytotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(Dicearraytotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(Dicearraytotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(Dicearraytotal5));
System.out.println("Total: " + total);
You are missing an end bracket to stop the for loop, so I assume you were attempting to print the arrays each iteration of the loop. I cleaned up your code a lot and you should take note on some of the changes in order to organize your code better which will make it easier to understand.
public static void main(String[] args) {
int[] diceArrayTotal1 = new int[10];
int[] diceArrayTotal2 = new int[10];
int[] diceArrayTotal3 = new int[10];
int[] diceArrayTotal4 = new int[10];
int[] diceArrayTotal5 = new int[10];
int[] totals = new int[10];
for (int i = 0; i < diceArrayTotal1.length; i++) {
diceArrayTotal1[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal2[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal3[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal4[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal5[i] = (int) (Math.random() * 6 + 1);
totals[i] = (diceArrayTotal1[i] + diceArrayTotal2[i] + diceArrayTotal3[i] + diceArrayTotal4[i] + diceArrayTotal5[i]);
}
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(diceArrayTotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(diceArrayTotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(diceArrayTotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(diceArrayTotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(diceArrayTotal5));
System.out.println("Totals: " + Arrays.toString(totals));
}
Additionally I added a totals array that keeps the total for each index instead of printing it every loop like you were doing. You did not add your compare code, so I cannot assist you with that. Let me know if you need any clarification on any changes. I ran this code and it successfully generated the arrays you need and the totals.
public static void main(String[] args) {
int[] results = new int[6]; // This array will hold the number of time each dice was rolled, so for example results[0] is how many 1 s you have results[5] is how many 6 you have
Random random = new Random();
for (int i = 0; i < 5; i++) { // roll the dice 5 times
results[random.nextInt(6)]++; //increase the counter of the appropriate value
}
boolean balut = false;
for (int i = 0; i < 6; i++) {
System.out.println("Number of " + (i+1) + ": " + results[i]);
if (results[i] == 5) {
balut = true;
}
}
if (balut) {
System.out.println("Balut!");
}
}
Here I implemented only the check for the Balut, but the main point is how I am couting the dices results. Hope it helps.
I made the arithmetic mean for whole the sorted array, but now i want to make the arithmetic mean for first sorted half and second sorted half of array.
Ex: My array is: 77, 99, 44, 55, 22, 88, 11, 00, 66, 33.
My code make in first place the sort.
The outcome of program is: 00 11 22 33 44 55 66 77 88 99.
Now i want to make the mean for first half:
00 11 22 33 44 and print it.
Then i want to make the mean for the second half:
55 66 77 88 99 and print it.
public class Array {
private double[] a;
private int NrElmts;
public Array(int max)
{ a = new double[max];
NrElmts = 0;
}
public void elements(double value)
{ a[NrElmts] = value;
NrElmts++;
}
public void print()
{ for(int j=0; j<NrElmts; j++)
System.out.print(a[j] + " ");
System.out.println("");
}
public void selectionSort()
{
int out, in, min;
for(out=0; out< NrElmts -1; out++)
{ min = out;
for(in=out+1; in< NrElmts; in++)
if(a[in] < a[min] )
min = in;
invertPositions(out, min); }
}
private void invertPositions(int one, int two)
{ double temp = a[one];
a[one] = a[two];
a[two] = temp;
}
public void mean()
{
int i;
double sum = 0;
for(i = 0; i < NrElmts; i++) {
sum+=a[i];}
double medie = sum/NrElmts;
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
}
Try this
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
To calculate the mean for 9, 2 and 7 you have to firstly add them all up, which equals 18 and then divide by how many there are - so 18 / 3 which is 6.
Although, you will have to account for the possibility of an odd list - if there's an odd amount of elements, say for example 1, 2, 3 the middle point of 3 - is 1.5 - and if you're iterating through indexes the iterative variable will count the middle point as 1. So it's a bit tricky, not sure what you'd want to do.Consider the following code though - it does exactly what you want, but with odd list sizes, it will just divide by a decimal value
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int size = numbers.size();
int iterativeHalf = size / 2;
float meanHalf = (float) size / 2;
float lowerMean = 0;
float upperMean = 0;
for (int i = 0; i < size; i++) {
int realRef = i + 1;
Integer value = numbers.get(i);
if (realRef > iterativeHalf) { //Should be calculating upper mean
if (upperMean == 0) { //if lowerMean is just a running total, not divided yet to get the mean
System.out.println("the lower mean for numbers is " + lowerMean + " / " + meanHalf);
lowerMean = (lowerMean) / meanHalf; //add last value + divide to set it to the mean
}
System.out.println("upper mean = " + upperMean + " + " + value + " = " + (upperMean + value));
upperMean = upperMean + value; //keep the upper values up total going
} else {
System.out.println("lower mean = " + lowerMean + " + " + value + " = " + (lowerMean + value));
lowerMean = lowerMean + value; //keep adding the lower halfs values up
}
}
//When it breaks, must divide upperMean by size to get mean
System.out.println("the upper mean for numbers is " + upperMean + " / " + meanHalf);
upperMean = (upperMean) / meanHalf;
System.out.println(" ");
System.out.println("FINAL lower mean = " + lowerMean);
System.out.println("FINAL upper mean = " + upperMean);
Output is:
lower mean = 0.0 + 10 = 10.0
lower mean = 10.0 + 20 = 30.0
the lower mean for numbers is 30.0 / 2.0
upper mean = 0.0 + 30 = 30.0
upper mean = 30.0 + 40 = 70.0
the upper mean for numbers is 70.0 / 2.0
FINAL upper mean = 35.0
FINAL lower mean = 15.0
This, for a [10, 20, 30, 40] will yield the output shown above but essentially (10+20)/2 as the lower mean and (30+40)/2 for the upper mean.
For [10, 20, 30, 40, 50] will yield (10 + 20) / 2.5 the lower mean and (30+40+50)/2.5 for the upper mean
Only take sum of half the array. Give one more element to your second or first half in case if your array size is odd.
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
Since you already have way to make mean for entire array, all you need to do is find mid position of array and then run from and to that point.
In your example: NrElmts is 10, so divide your NrElmnts by 2, so you can get mean for 1 to 5, and then 6 to 10 both 5 each.
Think about situation where you have odd number of elements in array, how do u want to do it, whether in first array or second. let me know if this need help as well.
Steps:
1) create a new variable say a1 to NrElmts/2, and go with your mean function from 1 to a1
2) go from a1+1 to NrElmnts
Let me know if you need any help.
I'm a complete beginner in Java who just recently got introduced to loops. I'm trying to do write a program that reads in a target and finds the first n such that 1 + 1/2 + 1/3 + ... + 1/n > target. The problem supplied a code with the initialization of n and sum missing as well as the condition of while and its statements missing.
I'm able to work out how to make the harmonic series loop, but I'm not sure what to set n with to stop the loop when it exceeds the target.We've not learned about arrays in class yet..
import java.util.Scanner;
/**
This program computes how many steps the sum 1 + 1/2 + 1/3 + ...
needs to exceed a given target.
*/
public class ReciprocalSum
{
public static void main(String[] args)
{
double sum = 0;
int n = ???? ;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
int i = 0;
//Notes
// 1 + 1/2 + 1/3 + 1/4 + ..... 1/n
//Make a loop that repeats itself starting with n = 1 --> 1/1 + 1/2 + 1/3 + 1/4 + 1/n
// 1.0/n + (1.0/ n - 1) + (1.0/n-2) +.... if n =4 --> 1/4 + 1/3 + 1/2 + 1/1 as long as n >0
while ( n > 0)
{
sum += 1.0/n ;
n--;
}
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}
n should be incremented in the loop (and therefore it should start at 0), and the loop should be exited when you reach the target:
int n = 0;
...
while (sum <= target)
{
n++;
sum += 1.0/n;
}
Because Java 8+ has lambdas, and you can generate a range 1 to n and perform your calculation and get the sum in one step. Basically, you could do
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble(), sum = 1.0;
int n = 1;
while (sum < target) {
sum = IntStream.range(1, n).mapToDouble(i -> 1.0 / i).sum();
n++;
}
System.out.printf("n=%d, sum=%.2f%n", n, sum);
You can achieve that in this way by calculating sum of the series until its sum bigger than the target value:
double sum = 0;
int n = 1;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
while(sum <= target){
sum = sum + 1.0/n;
n = n + 1;
}
System.out.println(sum);
I managed to solve this, below is my solution :
public class ProblemA001k {
public static void main(String[] args) {
System.out.println("Sum from 1" + " to " + divQ + ":" + sum2);
System.out.println();
divQ += q;
newQ += q;
sum1 = 0;
sum2 = 0;
}
key.close();
}
}
Now I was told to modify my solution so that it uses ONLY ONE LOOP.
I have 3 loops in the code above, even when I tried using only 2 loops I struggled. but ONE LOOP ? I don't know how to improve my code. Please help me.
This is a Mathematic problem.
If you know that you can find the sum of all integers from 1 to X, you just need to do X * (X+1) / 2.
You can find all the batch values easily.
Sum from 1 to 400: 80200
Sum from 401 to 450: 21275
Sum from 1 to 450: 101475
Will be found like this :
450 * 451 / 2 = 101475 (1 to 450)
400 * 401 / 2 = 80200 (1 to 400)
101475 - 80200 = 21275 (401 to 450)
With this, you can limit the loop to just calculate the values from q to n by incrementing by q
And a quick code to do it :
static void sum(int n, int q){
int i = q;
int sum, tmp=0;
while(i < n){
sum = i * (i+1) / 2;
System.out.println(String.format("Sum from %d to %d : %d", i-q+1 , i, sum - tmp));
System.out.println(String.format("Sum from %d to %d : %d", 1, i, sum));
tmp = sum;
i += q;
}
}
And I run it with
public static void main(String[] args){
sum(500, 50);
}
to have this result
Sum from 1 to 50 : 1275
Sum from 1 to 50 : 1275
Sum from 51 to 100 : 3775
Sum from 1 to 100 : 5050
Sum from 101 to 150 : 6275
Sum from 1 to 150 : 11325
Sum from 151 to 200 : 8775
Sum from 1 to 200 : 20100
Sum from 201 to 250 : 11275
Sum from 1 to 250 : 31375
Sum from 251 to 300 : 13775
Sum from 1 to 300 : 45150
Sum from 301 to 350 : 16275
Sum from 1 to 350 : 61425
Sum from 351 to 400 : 18775
Sum from 1 to 400 : 80200
Sum from 401 to 450 : 21275
Sum from 1 to 450 : 101475
The good think with this solution is the number of loop, this will increment by q instead of 1
Note : The solution is a quick implementation, this could be done better.
EDIT :
Thanks to Margaret Bloom in the comments to point out the name of this formula :) For more information, you are welcome to look at Triangular Number
This should do it:
int totalSum = 0;
int batchSum = 0;
for (int i = 1; i <= n; i++) {
totalSum += i;
batchSum += i;
if (i % q == 0) {
System.out.println("Sum from " + (i - q + 1) + " to " + i + ":" + batchSum);
System.out.println("Sum from 1 to " + i + ":" + totalSum);
batchSum = 0;
}
}
Edit:
The better Math way:
int lastTotalSum = 0;
for (int i = 1; i <= n / q; i++ ) {
int top = i * q;
int totalSum = top * (top + 1) / 2;
int batchSum = totalSum - lastTotalSum;
System.out.println("Sum from " + (top - q + 1) + " to " + top + ":" + batchSum);
System.out.println("Sum from 1 to " + top + ":" + totalSum);
lastTotalSum = totalSum;
}
I found a nice solution with java8 Streams:
int n=1000;
int q=50;
int length = n/q -1;
int[] previousSum={0};
IntStream.range(0, length).map(i -> (i+1)*q).forEach(s -> {
int sum=(s*(s+1))/2;
int batch = sum - previousSum[0];
previousSum[0] = sum;
System.out.println("Sum from " + (s - q + 1) + " to " + s + ":" + batch);
System.out.println("Sum from 1 to " + s + ":" + sum);
});
Do one loop iterating entire range and use indexes to decide whether to add, reset or print your sums.
Hope this gives your right idea, if you still dont know I can illustrate it a bit more.
I'm currently learning Java and I've just beginned so my knowledge of it is not very good.
I have a problem with a program I wrote that calculates the first 100 values of the Fibonacci sequence. The point is that it just outputs the 2 and no other number.
This is the code of my program:
class MyClass1 {
public static void main(String[ ] args) {
int[] fib = new int[102];
fib[0] = 1;
fib[1] = 1;
int counter = 0;
int n1, n2, fibSum;
while(counter < (fib.length - 2)){
n1 = fib[counter];
System.out.println(fib[counter]);
counter++;
n2 = fib[counter];
System.out.println(n2);
counter++;
fibSum = n1 + n2;
System.out.println(fibSum);
fib[counter] = fibSum;
}
}
}
Thank you for your help.
There are some logical errors in your code.
First loop:-
Initially n1=fib[0]=1 and n2=fib[1]=1 and you print both. fib[2] is the sum and so it is 2. So far so good.
Second loop:-
n1 = fib[2] = 2. n2 = fib[3] = 0 and hence fib[4] = 2. This is where the problem happens. Hence you will always see 2 0 2 in the output from second loop onwards.
For Fibonacci sequence, you need to add the previous 2 values but you are only considering the previous value in your code. Here's a corrected version of your code:-
public static void main(String[ ] args) {
double[] fib = new double[100];
fib[0] = 1;
fib[1] = 1;
int counter = 2;
double n1, n2, fibSum;
System.out.println(fib[0]);
System.out.println(fib[1]);
while(counter < fib.length){
n1 = fib[counter-1];
n2 = fib[counter-2];
fibSum = n1 + n2;
System.out.println(fibSum);
fib[counter] = fibSum;
counter++;
}
}
Note that I am using type double because type int or even long is not enough for going upto the 100th term in this sequence.
Fibonacci number is the sum of the previous 2 numbers:
fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)
So it can be evaluated very nice using recursion:
private static long fibonacci(int n) {
if (n <= 1) return n;
else return fibonacci(n - 1) + fibonacci(n - 2); }
public static void main(String[] args) {
int n = 102;
for (int i = 1; i <= n; i++)
System.out.println(i + ": " + fibonacci(i));
}
Your problem is that
A) all array values are initialized to 0
B) you are accessing "the next" array value, before assigning a value to it!
When you change your outputs to:
System.out.println("1. counter: " + counter + "/" + fib[counter]);
counter++;
n2 = fib[counter];
System.out.println("2. counter: " + counter + "/" + fib[counter]);
counter++;
fibSum = n1 + n2;
fib[counter] = fibSum;
System.out.println("3. counter: " + counter + "/" + fib[counter]);
You will find that it prints:
1 counter: 0/1
2 counter: 1/1
3 counter: 2/2
1 counter: 2/2
2 counter: 3/0
The last row shows you what is going on: you fetch the value at index 3 ... before you assigned a value to it. Therefore your whole fibonacci sum ... doesn't "start"; because you keep loosing values.
In other words: you have to ensure that your counter increases properly:
while(counter < (fib.length - 2)){
n1 = fib[counter];
System.out.println("1 counter: " + counter + "/" + fib[counter]);
n2 = fib[counter+1];
System.out.println("2 counter: " + counter + "/" + fib[counter+1]);
fibSum = n1 + n2;
fib[counter+2] = fibSum;
System.out.println("3 counter: " + counter + "/" + fib[counter+2]);
counter++;
}
Meaning: you need one full loop for each value of counter. When you run my solution, you will find that it works nicely (until counter hits 44/45 and we run into int overflow; as the numbers get too big).
After your first iteration you'll have the following values:
n1 = 1
n2 = 1
fibsum = 2
fib[2] = 2
All other values from fib[3] to length are uninitialized.
So in the second iteration :
n1 = 2
now the counter value will be increased by 1 which is counter = 3
n2 = fib[3]
// this one in not calculated properly and hence the issue.