With this program i read and compare the numbers that I'm given in a text file and print out "buy" whenever the number goes up three consecutive time and "sell" whenever the number goes down three consecutive times.
The program runs perfectly but at the end i get
java.lang.ArrayIndexOutOfBoundsException
All i want is a way to get unlimited numbers as an argument and dont have to change the array number([15]) every time i want to read a txt file.
public class Practise1
{
public static void main(String [] args)
throws IOException
{
int num=0;
String choice;
int up=0;
int down=0;
int same=0;
FileInputStream w = new FileInputStream("numbers.txt");
Scanner scanner = new Scanner(w);
while(scanner.hasNextDouble())
{
Double [] con= new Double [15];
for (int i=0; i<con.length; i++)
{
con[i]=scanner.nextDouble();
}
for (int a=0; a<con.length&&a<con.length; a++)
{
num++;
System.out.print(num+" "+(con[a]));
if(con[a]<con[a+1])
{
up++;
}
else if(con[a]>con[a+1])
{
down++;
}
else
{
same++;
}
if ((up >= 3 && (down > 1 || same >= 1)))
{
System.out.print(" "+"sell");
up=0;
same=0;
}
else if ((down >= 3 && (up > 1 || same >= 1)))
{
System.out.print(" "+"buy");
down=0;
same=0;
}
System.out.println();
}
}
scanner.close();
}
}
The result i get :
1 26.375
2 25.5
3 25.125
4 25.0
5 25.25 buy
6 27.125
7 28.25
8 26.0 sell
9 25.5
10 25.0
11 25.125 buy
12 25.25
13 26.375
14 25.5 sell
15 25.5
java.lang.ArrayIndexOutOfBoundsException: 15
at Practise1.main(Practise1.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)