import java.util.ArrayList;
import java.util.Iterator;
/**
* Some exercises to practice the concepts of looping and arraylists
*
* Looping through multiples of 5 between 10 and 95
* Adding up all numbers between 2 integers
* Testing if a number is a prime
*
* @author Justin Chan
* @version v.1
*/
public class Looptester
{
private ArrayList<Integer> modValues;
private int[] modValues2;
/**
* Constructor for objects of class tester
*/
public Looptester()
{
modValues = new ArrayList<Integer>();
}
/**
* Tests is a number is a prime using an Array
*
* @return True if it is a prime, false if it is not
* @param n The number whose status as a prime number you wish to find out
*/
public boolean arrayPrime(int n)
{
modValues2 = new int[n - 2];
int nextIndexNumber = 0;
boolean hasZero = true;
//x is the divisor, goes from 2 to n-1 inclusive
for(int x = n - 1; x > 1 ; x--)
{
//x value loops through all numbers between 1 and n-1
modValues2[nextIndexNumber] = (n % x);
nextIndexNumber++;
}
for(int modValue : modValues2)
{
if(modValue != 0)
{
//there are no 0s in the Array
//it is a prime
hasZero = true;
}
else
{
//there is a 0 in the Array
//it is not a prime
hasZero = false;
}
}
//empty Array for subsequent method calls
modValues2 = new int[n];
return hasZero;
}
/**
* Tests is a number is a prime using a for-loop
*
* @return True if it is a prime, false if it is not
* @param n The number whose status as a prime number you wish to find out
*/
public boolean isPrime(int n)
{
boolean isPrime = true;
for(int i = 2; i < n; i++)
{
if(n % i == 0)
{
isPrime = false;
//break;
}
}
return isPrime;
}
/**
* Tests is a number is a prime using an ArrayList
*
* @return True if it is a prime, false if it is not
* @param n The number whose status as a prime number you wish to find out
*/
public boolean arrayListPrime(int n)
{
int x = n; //x is the divisor, goes from 2 to n-1 inclusive
while(x > 2)
{
x--; //x value loops through all numbers between 1 and n-1
modValues.add(n % x);
}
if(modValues.contains(0) == false) //can't find a 0 in modValues, is prime
{
//empties array
modValues = new ArrayList<Integer>();
return true;
}
else //there is a 0 in modValues, is prime
{
//empties array
modValues = new ArrayList<Integer>();
return false;
}
}
}