I'm working on some homework programs and I'm required to do stuff in Java using functional programming principles as much as possible. These are the important bits of a program that receives a list of numbers and prints the even ones:
public static void main( String args[ ] )
{
ArrayList<Double> listEven = new ArrayList<Double>();
inputRecursion( );
outputRecursion( );
}
public static void inputRecursion( )
{
Scanner in = new Scanner( System.in );
if( in.hasNextDouble() )
{
if( (in.nextDouble() % 2) == 0 )
{
listEven.add( in.nextDouble() );
}
inputRecursion( );
}
}
public static void outputRecursion( )
{
Iterator<Double> it = listEven.iterator();
if( it.hasNext() )
{
System.out.println( it.next() );
outputRecursion( );
}
}
It's a work in progress, but I haven't got to run it and check the logic because I still have two compilation errors in the lines:
listEven.add( in.nextDouble() );
Iterator<Double> it = listEven.iterator();
These two lines throw "cannot find symbol", and I know this is because the ArrayList was declared in a way that makes in inaccessible from methods outside main. I have a rough understanding of the ways of fixing this. I know about setters and getters and they look simple enough from what I researched, but I consider those the last resource since I'm trying to avoid the use of variables (I am aware that my program has other mutable stuff; I'm working on it) in order to meet the restrictions of the exercise as much a possible. I also know that I can make it public static, but then that causes like 15 more errors to appear, and from what I looked up it requires to be "initialized" and it also involves variables.
Are there any other ways to make the ArrayList accessible from those two methods? I'm specially interested in ways that don't involve variables or iteration.
Declare the ArrayList
as static but outside of the main function like below:
static ArrayList<Double> listEven = new ArrayList<Double>();
public static void main( String args[ ] )
{
inputRecursion( );
outputRecursion( );
}
public static void inputRecursion( )
{
Scanner in = new Scanner( System.in );
if( in.hasNextDouble() )
{
if( (in.nextDouble() % 2) == 0 )
{
listEven.add( in.nextDouble() );
}
inputRecursion( );
}
}
public static void outputRecursion( )
{
Iterator<Double> it = listEven.iterator();
if( it.hasNext() )
{
System.out.println( it.next() );
outputRecursion( );
}
}