//  Scott DeRuiter      7/8/2002
//  Primes.java
//  Find all primes from 1 to n, where the user chooses n.
//  7/15/2011 - Greenstein: Changed TextReader to Scanner

import java.util.Scanner;

public class Primes   
{
	
	private int max;

	public Primes ( )   
	{
		max = 0;
	}
	
	public static void main ( String [] args )   
	{
		Primes p = new Primes ( );
		p.GetMax ( );
		p.FindAndPrintPrimes ( );
	}

	public void GetMax ( )   
	{
		Scanner input = new Scanner ( System.in );
		do  
		{
			System.out.print ( "\n\nEnter the max possible prime (2 to 100000) ->   " );
			max = input.nextInt ( );
		}  while ( max < 2 || max > 100000 );
	}

	public void FindAndPrintPrimes ( )   
	{
		for ( int i = 2; i <= max; i++ )   
		{
			if ( IsPrime ( i ) )
				System.out.println ( i );
		}
	}

	public boolean IsPrime ( int value )   
	{
		for ( int j = 2; j < value; j++ )  
		{
			if ( value % j == 0 )
				return false;
		}
		return true;
	}
}

Back to Lesson 8 Examples

Back to Java Main Page