Question:
Need help figuring out why java program doesn't work correctly?
fwahobadagadz
2008-11-07 18:54:47 UTC
This program should take up to 25 integers, store them into an array, and return the longest increasing sequence of numbers in the array. However, it seems to always return 1 as the value of count. 10 points to whoever can help me fix it, thanks!

import java.util.*;

public class Sequence
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [] x = new int[25];
System.out.println("Enter up to 25 numbers then -999 to stop");
x[0] = input.nextInt();
int count = 0;

for (int i = 1; x[i-1]!=-999 && i<25; i++)
{
x[i] = input.nextInt();
}

for (int i = 1; i<25; i++)
{

int temp = 0;
if (x[i] > x[i-1])
temp++;
else
temp = 0;
if (temp > count)
count = temp;
}

System.out.println("The longest increasing sequence is: " + count);
}

}
Three answers:
Arjun
2008-11-07 19:22:37 UTC
u hav return loop like this.

for (int i = 1; i<25; i++)

{



int temp = 0;

if (x[i] > x[i-1])

temp++;

else

temp = 0;

if (temp > count)

count = temp;

}





declare temp out side it is assigning to zero for every iteration ...

write it like this ...

int temp=0;

for (int i = 1; i<25; i++)

{

if (x[i] > x[i-1])

temp++;

else

temp = 0;

if (temp > count)

count = temp;

}





now it ll return correct longest increasing seq..
gena
2016-05-26 12:54:15 UTC
The problem is that the loop goes over the limit of the array, you have: for (i=0;i<=2;i=i++) Means that i will go over 0 1 and 2, but k[2] is not accesable because k is an array of only 2 elements and you have only k[0] and k[1], either make k an array of 3 elements or make the for loop like this: for (i=0;i<2;i=i++) Or better yet: for (i=0;i
?
2008-11-07 19:24:15 UTC
I'm finding a few things wrong.



First I would use a while to get input. But regardless....

Your second for loop:

you are resetting temp each time.

count is never accumulating

should be count+=temp.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...