Results 1 to 19 of 19
  1. #1
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Question Help in object oriented programming .

    Hi

    I had to write a java application , which contains code to run either one of the application from choice of 2 application.

    I am trying my best to explain , so that someone can help me , write a better java code.

    In real world example ,
    say their is a school project :-
    having a choice to run
    1)pay roll for teachers
    2)fees for students
    And it is a console application

    choice 1 entered , it runs pay roll for teachers .

    My application is similar to the real world example.

    I wrote everything in one class.But now i want to create 2 classes , one for 1)choice one application (from above example ..it is running just the pay roll for teachers .
    second for 2)choice two application
    (from above example ..just running fees for students.

    Can anyone help me in writing 3 different classes.
    I am posting my code here ...


    MAINCLASS :-

    Java Code:
    package school;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintStream;
    import java.io.Writer;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.Scanner;
    
    import oracle.jdbc.driver.OracleTypes;
    
    public class MainClass {
    
    	static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    
    //	Global Variable : 
    	public static String DATABASE_URL;
    	public static int Count_DeletedRows;
    	public static int outputCount = 0;
    	public static String pathOfFile;
    	private static Connection connection;
    	private static Statement statement;
    	 
    //	Global Variable : Six Output Files 
    	public static String AuditFile1;
    	public static String AuditFile2;
    	public static String OutputFile;
    	public static String DCNVOutput;
    	
    	public static void main(String[] args) throws ClassNotFoundException {
    
    //		Local Variables :
    		int yrfrom;
    		int yrto;
    		int lnfrom;
    		int lnto;
    		int recCount = 0;
    
    		String DBServer = System.getProperty("DBServer","DEV");
    		System.out.println("server is " +DBServer);
    		if(DBServer.equals("QA")){
    			System.out.println("Entered the QA area");
    			DATABASE_URL =" jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ....";
    		}else if(DBServer.equals("PROD")){
    			System.out.println("The default is PROD");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = .....";
    		}else {
    			System.out.println("Entered the DEV area");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ......";
    		}
    
    		pathOfFile = System.getenv("TEMP");
    		Scanner scan = new Scanner(System.in); 
    		System.out.println("Please enter desired task number:");
    		System.out.println("1 =Pay roll for teachers");
    		System.out.println("2 =fees for students");
    		int enteredVal = scan.nextInt();
    
    		if (enteredVal==1)
    		{
    			Class1 class1 = new Class1();
    			String process = class1.process("PAY ROLL INFORMATION");
    			System.out.println("process :"+process);
    
    //			Calling the procedure to enter all the input values required.
    			String user_id = f_userid(scan);	
    			String password = f_password(scan);
    			dbConnect(user_id, password);
    			int year = f_year(scan);
    			int DataName = f_dataName(scan);
    			int dataset = f_dataSet(scan); 
    //			Here we enter the input filename with fully qualified path
    			try {
    				File readin = null;                                                                          
    				boolean gettingFilename = true;
    			while(gettingFilename) {
    					System.out.println("Enter fully qualified file name: ");
    					String inFile = scan.next();					
    					readin = new File(inFile);
    					if(readin.exists()){
    						System.out.println("All Parameters are entered by User ");
    						Filename myHomePage = new Filename(inFile, '\\', '.');
    						String Filename = myHomePage.filename(); 
    						OutputFile = pathOfFile + "\\EXTRACT_" + Filename + ".tsv";
    						System.out.println("The output file is located at:"+OutputFile);
    						AuditFile1 = pathOfFile + "\\Audit_" + Filename + ".txt";
    						System.out.println("The Audit file is located at:"+AuditFile1);
    
    						gettingFilename = false;						 
    					}else{                                                                                                                                              
    						System.out.println("File Not Found");
    					}			 
    				}	
    
    //				The results of all System.out.println's are captured in this Audit file.
    				try {					
    					System.setOut(new PrintStream(new FileOutputStream(new File(AuditFile1),false)));
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    				}
    
    //				Truncate the EXTRACT_CCLNS table before processing
    				f_truncate();
    //				Reset the sequence to 1.
    				sequence();				
    
    //				FIRST STEP	: Here I open the input file and read in record by record 
    				Scanner in = new Scanner(readin);
    				while (in.hasNextLine()){
    					String input = in.nextLine();
    					recCount++;		
    					String[] column = input.split(",");
    					int columnCount = column.length;				
    					if(columnCount == 4){
    //						the String to integer conversion happens here for each field of the record read.
    						yrfrom = Integer.parseInt(column[0].trim());
    						yrto = Integer.parseInt(column[1].trim());
    						lnfrom = Integer.parseInt(column[2].trim());
    						lnto = Integer.parseInt(column[3].trim());
    
    //						First IF statement B = A	
    						if(yrto == yrfrom){
    							//1 .BEGIN 
    							if(lnto == lnfrom){								
    //								Executing the procedure.								
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);				
    							}else if(lnto > lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);	
    							}else{
    								System.out.println("The LNTO IS LESSTHAN THE LNFROM : SO NO PROCESSING OF THIS RECORD");
    							}
    						}else if(yrto > yrfrom){
    							//2.BEGIN
    							if(lnto == lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);										
    							}else if(lnto > lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);												
    							}else{
    								System.out.println("The LNTO IS LESSTHAN THE LNFROM : SO NO PROCESSING OF THIS RECORD");
    							}						
    						}else{
    							System.out.println("THE YRTO IS LESSTHAN THE YRFROM : SO NO PROCESSING OF THIS RECORD");
    						}
    					}else{
    						System.out.println("THE INPUT FILE HAS COLUMN SIZE GREATER THAN 4 FOR THIS RECORD");
    					}
    				}
    			}catch(FileNotFoundException e){
    				e.printStackTrace();
    			}			
    
    
    		}else if (enteredVal==2)
    		{  			
    			Class2 class2 = new Class2();
    			String process = class2.process("FEES FOR STUDENTS");
    			System.out.println("process :"+process);	
    
    			scan = new Scanner(System.in);  
    //			Calling the procedures to get the input values .
    			String user_id = f_userid(scan);	
    			String password = f_password(scan);
    			dbConnect(user_id, password);
    			int year = f_year(scan);
    			int DataName = f_dataName(scan);
    			
    
    //			The path of the Output file 
    			FEESOutput = pathOfFile + "\\FEES_COMPARE.csv"; 
    			
    //			The results of all System.out.println's are captured in this Audit file.
    			try {					
    				System.setOut(new PrintStream(new FileOutputStream(new File(AuditFile2),false)));
    			} catch (FileNotFoundException e) {
    				e.printStackTrace();
    			}		
    //			Calling the procedure which gives us an output file for fees compare.
    			f_feescompare(year,.....);			
    		} else {
    			System.err.println("EXIT THE PROGRAM AND RUN AGAIN");
    			System.exit(1);
    		}	
    	}
    
    	private static void dbConnect(String user_id, String password){
    		try {
    			Class.forName(JDBC_DRIVER);	
    			connection = DriverManager.getConnection(DATABASE_URL,user_id,password);
    			connection.setAutoCommit(false);
    			statement = connection.createStatement();
    		} catch (SQLException e) {
    			String temp = e.getMessage();
    			temp = temp.replaceAll(temp, "Login Error: improper username and/or password! /n");
    			System.err.println("ERROR MESSAGE IS:"+temp);
    			System.exit(1);
    		} catch (ClassNotFoundException e) {
    			System.err.println("Database URL Not Found! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}
    	private static void dbClose() {
    		try {
    			statement.close();
    			connection.close();
    			System.exit(1);
    		}catch (SQLException e){
    			System.err.println(" Error Closing Database Connection! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}
    	private static void f_truncate() {
    		String SqlDel = ("DELETE FROM ......"); 
    		try {
    			Count_DeletedRows = statement.executeUpdate(SqlDel);
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    	}
    	
    	
           private static int f_year(Scanner scan) {
    		Calendar cal = new GregorianCalendar();
    		int years = cal.get(Calendar.YEAR); 
    		System.out.println("Enter the 4 digit year: ");
    		int year = scan.nextInt();  //Scan the input
    		while(year< 2004 || year > years){
    			System.out.println("Invalid Year.Year cannot be lessthan 2004 and greaterthan current year");
    			System.out.println("Enter the 4 digit year:");
    			year = scan.nextInt();
    		}
    		return year;
    	}
    	private static String f_password(Scanner scan) {
    //		char[] paswd=System.console().readPassword("Enter password:");
    ////		Thread.currentThread();
    ////		Thread.sleep(1);
    //		String password = new String(paswd);
    //		System.out.println("The value of the password got from the console is:"+password);
    //		-----
    		System.out.println("Enter password: ");
    		String password = scan.next();  //Scan the input 
    		return password;
    	}
    	private static String f_userid(Scanner scan) {
    		System.out.println("Enter user id: ");
    		String user_id = scan.next();  //Scan the input 
    		int userlen = user_id.length();
    		while(userlen != 5){	
    			System.out.println("The user id is less than 5 characters long .PLEASE ENTER RIGHT USER ID ");
    			System.out.println("Please enter userid again of 5 characters length: ");
    			user_id = scan.next();  //Scan the input 
    			userlen = user_id.length();
    		}
    		return user_id;
    	}
    	private static void f_extract(String user_id, int year, int DataName,int dataset) {		
    /		CallableStatement proc_stmt;		
    
    		try {	
    			FileOutputStream fos;	
    			fos = new FileOutputStream(new File(OutputFile),false);
    			Writer out = new OutputStreamWriter(new BufferedOutputStream(fos));
    			proc_stmt = connection.prepareCall("{? = call F_CREATE_HEADER(?)}");	
    //			Register the type of the return value		
    			proc_stmt.registerOutParameter(1,OracleTypes.VARCHAR);			   
    			proc_stmt.setString(2,user_id);
    //			Execute and retrieve the returned value
    			// Execute and retrieve the returned value
    			proc_stmt.execute();
    			String  retValue = proc_stmt.getString(1);
    			out.write(retValue);
    			out.write("\r\n");
    			proc_stmt.close();
    
    //			Call a function with four IN parameter; the function returns a VARCHAR
    			proc_stmt = connection.prepareCall("{? = call F_MAIN(?,?,?,?)}");
    			// Register the type of the return value
    			proc_stmt.registerOutParameter(1,OracleTypes.CURSOR);		   
    			proc_stmt.setString(2,user_id);
    			proc_stmt.setInt(3,DataName);
    			proc_stmt.setInt(4,year);
    			proc_stmt.setInt(5,dataset);
    			// Execute and retrieve the returned value
    			proc_stmt.execute();
    			ResultSet rs = (ResultSet) proc_stmt.getObject(1); // So, here it works. 
    			//print the results
    			int count = 0;
    			int ncols = rs.getMetaData().getColumnCount();
    
    //			for (int i=1; i<(ncols+1); i++) {
    //			out.append(rs.getMetaData().getColumnName(i));
    //			if (i<ncols){ 
    //			out.append(",");
    //			}else{
    //			out.append("\r\n");
    //			}
    //			}
    			while (rs.next()) {
    				count++;
    				for (int i=1; i<(ncols+1); i++) {
    					out.append(rs.getString(i));
    					if (i<ncols){
    						out.append(",");
    					} else{ out.append("\r\n");
    					}
    				}	
    			}
    			System.out.println("THE NUMBER OF RECORDS IN THE OUTPUT FILE ARE:"+count);
    			proc_stmt.close();
    			out.flush();
    			out.close();
    		}catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	private static void sequence() {
    		try{
    			//run the sequence procedure here .
    			CallableStatement proc_stmt = connection.prepareCall("{call P_RESET_SEQUENCE}");				            	
    			proc_stmt.executeQuery();
    		}catch (SQLException sqle){    								
    			System.err.println("\nSQLException:\n");
    			System.err.println("SQLState: "+sqle.getSQLState());
    			System.err.println("Message: "+ sqle.getMessage());
    		}
    	}
    	private static void f_dbInsert(int yrfrom, int yrto, int lnfrom, int lnto,
    			String user_id) {
    		try {
    		
    			CallableStatement proc_stmt = connection.prepareCall("{call P_INSERTMORE_PROC(?,?,?,?,?)}");
    			proc_stmt.setString(1,user_id);
    			proc_stmt.setInt(2,yrfrom);
    			proc_stmt.setInt(3,yrto);
    			proc_stmt.setInt(4,lnfrom);
    			proc_stmt.setInt(5, lnto);
    			proc_stmt.executeQuery();
    			proc_stmt.close();
    		}catch (SQLException sqle){    								
    			System.err.println("\nSQLException:\n");
    			System.err.println("SQLState: "+sqle.getSQLState());
    			System.err.println("Message: "+ sqle.getMessage());
    		}
    	}
    	
    	public static void f_feecompare(int year,......){
    			
    		// Call a function with two IN parameters; the function returns a cursor
    		CallableStatement proc_stmt = null;
    
    		try {
    			FileOutputStream fos;					
    			fos = new FileOutputStream(new File(DCNVOutput));					
    			Writer out = new OutputStreamWriter(new BufferedOutputStream(fos));		
    			proc_stmt = connection.prepareCall("{? = call F_CREATE_HEADER}");
    //			Register the type of return value
    			proc_stmt.registerOutParameter(1,OracleTypes.VARCHAR);
    //			Execute and retrieve the returned value
    			proc_stmt.execute();
    			String retValue = proc_stmt.getString(1);
    			out.write(retValue);
    			out.write("\r\n");
    //			Call a function with seven IN parameters; the function returns a cursor.
    			proc_stmt = connection.prepareCall("{? = call F_2_IDS(?,?,?,?,?,?,?)}");	
    //			Register the type of the return value		
    			proc_stmt.registerOutParameter(1,OracleTypes.CURSOR);			   
    			proc_stmt.setInt(2,year);
    			proc_stmt.setString(3,facilityname);
    			proc_stmt.setInt(4, DataName);
    			proc_stmt.setString(5, fee1);
    			proc_stmt.setString(6, version1);
    			proc_stmt.setString(7, fee2);
    			proc_stmt.setString(8, version2);			
    //			Execute and retrieve the returned value
    			proc_stmt.execute();
    			ResultSet rs = (ResultSet) proc_stmt.getObject(1); // So, here it works. 
    			//print the results
    			int count = 0;
    			int ncols = rs.getMetaData().getColumnCount();
    
    			while (rs.next()) {
    				count++;
    				for (int i=1; i<(ncols+1); i++) {
    					out.append(rs.getString(i));
    					if (i<ncols){
    						out.append(",");
    					} else{ out.append("\r\n");
    					}
    				}	
    			}
    			System.out.println("THE NUMBER OF RECORDS IN THE OUTPUT FILE ARE:"+count);
    			proc_stmt.close();
    			out.flush();
    			out.close();
    		}catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			System.out.println(e.toString());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			System.out.println(e.toString());
    		} catch (SQLException e) {
    			String temp = e.getMessage();
    			temp = temp.replaceAll(temp, "A ID COULD NOT BE LOCATED ..BECAUSE OF WRONG INPUTS");
    			System.err.println("ERROR MESSAGE IS:"+temp);
    		} 
    	}
    
    }
    CLASS1 :-
    Java Code:
    public class Class1 {
    	
    
    	public String process(String str)
    	{
    		
    		return str+ "PROCESSING BEGAN";
    	}
    	
    }
    cAN ANYONE ..tell me , what to include in the Class1 class from MAINCLASS class .

    so that main class looks simplier..then having all code at one place.

    I am learning object oriented programming ..

    need help ..in writing this project.

    All the code is their in MAINCLASS.

    Thanks in advance .
    Last edited by renu; 10-19-2010 at 10:22 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I know you don't want to hear this, but you are far better off taking a stab at this first yourself, to create classes, test them, modify them, then to ask us for advice at this stage. Then when you run into a difficulty, you can show us what you've tried, and ask much more specific questions. My experience has been that it's in doing the attempt that you learn, and to miss out on that experience risks cheating yourself out of learning.

    Best of luck.

  3. #3
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    I tried doing it .

    I am confused ..in what to remove and what to add in class1.

    If u can suggest some ideas..i will try it

    I think the mainclass ..should contains all the methods and they should be public .

    class1 should call those methods ...when choice 1 is made the if loop is entered and it calls class1 ..

    But i am not having any success.

    As the inputs to this java program are console inputs.

    and the paramters to the methods written above have scan method in it ..
    Any help is appreciated ...so that i will have an idea to follow ..

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    As I see it:
    Class 1 is TeachPayRoll: This contains all information needed to run this portion of the program.
    Class 2 is StudentFees: This contains all information needed to run this portion of the program.
    Class 3 is Main: This runs the menu, and creates and interacts with a TeacherPayRoll object and a StudentFees object. This should be small.

  5. #5
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    As I see it:
    Class 1 is TeachPayRoll: This contains all information needed to run this portion of the program.
    Class 2 is StudentFees: This contains all information needed to run this portion of the program.
    Class 3 is Main: This runs the menu, and creates and interacts with a TeacherPayRoll object and a StudentFees object. This should be small.
    public class Class1 {


    public String process(String str)
    {
    ///??????????should all the methods like f_userid , f_password ..should come here .....
    return str+ "PROCESSING BEGAN";
    }

    }

  6. #6
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Quote Originally Posted by renu View Post
    public class Class1 {


    public String process(String str)
    {
    ///??????????should all the methods like f_userid , f_password ..should come here .....
    return str+ "PROCESSING BEGAN";
    }

    }
    Can you pls ..help me with a piece of code ..from my first mail ..to understand better .

    Your help is very much appreciated..
    I learnt a new word today ..how to say in java

    Saying object ...

    Class 3 is Main: This runs the menu, and creates and interacts with a TeacherPayRoll object and a StudentFees object.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    First off, don't name your class ClassX such as Class1, but instead give it a logical name that makes sense for what it does, such as TeacherPayroll. Nextly, I'm not going to go through all that code in your first post, sorry, it's too much code and I have work to complete before I can go home, but if the method you are showing is something that an independent TeacherPayroll class would have, then it should be included inside of that class, and should be a non-static method.

  8. #8
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Thank You for all the guidance .

    I get this error after the changes have been made and i creating 3 classes .

    I will show you ,how my code looks and where it is pointing to when i debug the code by modifying the first post i have posted .

    Pls look at it and guide me in solving the error .

    Need help ...

  9. #9
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Unhappy

    First MainClass :- which will contain instances of other 2 classes .

    Java Code:
    package school;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.Scanner;
    import oracle.jdbc.driver.OracleTypes;
    
    public class MainClass {
    
    public static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    
    //	Global Variable : 
    	public static String DATABASE_URL;
    	private static Connection connection;
    	private static Statement statement;
    	 
    	public static void main(String[] args) throws ClassNotFoundException {
    
    		String DBServer = System.getProperty("DBServer","DEV");
    		System.out.println("server is " +DBServer);
    		if(DBServer.equals("QA")){
    			System.out.println("Entered the QA area");
    			DATABASE_URL =" jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = .......";
    		}else if(DBServer.equals("PROD")){
    			System.out.println("The default is PROD");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ........";
    		}else {
    			System.out.println("Entered the DEV area");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ........";
    		}
    
    		Scanner scan = new Scanner(System.in); 
    		System.out.println("Please enter desired task number:");
    		System.out.println("1 =payroll for Teachers");
    		System.out.println("2 =fees for students");
    		int enteredVal = scan.nextInt();
    
    		if (enteredVal==1)
    		{
    			payExtraction class1 = new payExtraction();
    			[COLOR="Red"]String process = class1.process("PAY DATA EXTRACTION ");[/COLOR]	--------------------------------> [COLOR="DarkOrchid"]60 th line in the code[/COLOR]		System.out.println("process :"+process);
    		}else if (enteredVal==2)
    		{  			
    			feesStudent class2 = new feesStudent();
    			String process = class2.process("FEES FOR STUDENT ");
    			System.out.println("process :"+process);		
    		}else
    		{
    			System.err.println("EXIT THE PROGRAM AND RUN AGAIN");
    			System.exit(1);
    		}	
    	}
    
    	public void dbConnect(String user_id, String password){
    		try {
    			Class.forName(JDBC_DRIVER);	
    			connection = DriverManager.getConnection(DATABASE_URL,user_id,password);
    			connection.setAutoCommit(false);
    			statement = connection.createStatement();
    		} catch (SQLException e) {
    			String temp = e.getMessage();
    			temp = temp.replaceAll(temp, "Login Error: improper username and/or password! /n");
    			System.err.println("ERROR MESSAGE IS:"+temp);
    			System.exit(1);
    		} catch (ClassNotFoundException e) {
    			System.err.println("Database URL Not Found! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}
    	public void dbClose() {
    		try {
    			statement.close();
    			connection.close();
    			System.exit(1);
    		}catch (SQLException e){
    			System.err.println(" Error Closing Database Connection! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}
    	
    	
    	public int f_year(Scanner scan) {
    		Calendar cal = new GregorianCalendar();
    		int years = cal.get(Calendar.YEAR); 
    		System.out.println("Enter the 4 digit year: ");
    		int year = scan.nextInt();  //Scan the input
    		while(year< 2004 || year > years){
    			System.out.println("Invalid Year.Year cannot be lessthan 2004 and greaterthan current year");
    			System.out.println("Enter the 4 digit year:");
    			year = scan.nextInt();
    		}
    		return year;
    	}
    	public String f_password(Scanner scan) {
    //		char[] paswd=System.console().readPassword("Enter password:");
    ////		Thread.currentThread();
    ////		Thread.sleep(1);
    //		String password = new String(paswd);
    //		System.out.println("The value of the password got from the console is:"+password);
    //		-----
    		System.out.println("Enter password: ");
    		String password = scan.next();  //Scan the input 
    		return password;
    	}
    	public String f_userid(Scanner scan) {
    		System.out.println("Enter user id: ");
    		String user_id = scan.next();  //Scan the input 
    		int userlen = user_id.length();
    		while(userlen != 5){	
    			System.out.println("The user id is less than 5 characters long .PLEASE ENTER RIGHT USER ID ");
    			System.out.println("Please enter userid again of 5 characters length: ");
    			user_id = scan.next();  //Scan the input 
    			userlen = user_id.length();
    		}
    		return user_id;
    	}	
    }

    Class1 :- ie., payExtraction .
    Java Code:
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintStream;
    import java.io.Writer;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Scanner;
    import java.sql.CallableStatement;
    
    import oracle.jdbc.OracleTypes;
    
    
    public class payExtraction {
    
    
    	public static  String AuditFile1;
    	public static String OutputFile;
    	public static String pathOfFile;
    //	public static int Count_DeletedRows;
    
    	private static Connection connection;
    	private static Statement statement;
    
    //	Local Variables :
    	int yrfrom;
    	int yrto;
    	int lnfrom;
    	int lnto;
    	int recCount = 0;
    	String user_id;
    	String password;
    
    	public String process(String str)
    	{
    		MainClass task = new MainClass();	
    		Scanner scan = new Scanner(System.in);
    		pathOfFile = System.getenv("TEMP");
    		user_id = task.f_userid(scan);
    		System.out.println("The value of user_id is:"+user_id);
    		password = task.f_password(scan);
    		task.dbConnect(user_id, password);
    		int year = task.f_year(scan);
    		int dataset = f_dataSet(scan); 
    //		Here we enter the input filename with fully qualified path
    		try {
    			File readin = null;                                                                          
    			boolean gettingFilename = true;
    			while(gettingFilename) {
    				:
    					:
    						if(readin.exists()){
    							:
    								:
    						}else{                                                                                                                                              
    							System.out.println("File Not Found");
    						}			 
    			}	
    
    
    //			Truncate the EXTRACT_CCLNS table before processing
    			[COLOR="Red"]f_truncate(); [/COLOR] ----------------------------------------------------------> ERROR starts here ???????????
    //					Reset the sequence to 1.
    					sequence();				
    
    //			FIRST STEP	: Here I open the input file and read in record by record 
    			Scanner in = new Scanner(readin);
    			while (in.hasNextLine()){
    				String input = in.nextLine();
    				recCount++;		
    				String[] column = input.split(",");
    				int columnCount = column.length;				
    				if(columnCount == 4){
    //					the String to integer conversion happens here for each field of the record read.
    					yrfrom = Integer.parseInt(column[0].trim());
    					yrto = Integer.parseInt(column[1].trim());
    					lnfrom = Integer.parseInt(column[2].trim());
    					lnto = Integer.parseInt(column[3].trim());
    
    //					First IF statement B = A	
    					if(ccto == ccfrom){
    						//1 .BEGIN 
    						if(lnto == lnfrom){								
    //							Executing the procedure.								
    							f_dbInsert(ccfrom, ccto, lnfrom, lnto,user_id);				
    						}else if(lnto > lnfrom){
    							f_dbInsert(ccfrom, ccto, lnfrom, lnto,user_id);	
    						}else{
    							System.out.println("The LNTO IS LESSTHAN THE LNFROM : SO NO PROCESSING OF THIS RECORD");
    						}
    					}else if(ccto > ccfrom){
    						:
    							:
    					}else{
    						System.out.println("THE INPUT FILE HAS COLUMN SIZE GREATER THAN 4 FOR THIS RECORD");
    					}
    				}
    			}catch(FileNotFoundException e){
    				e.printStackTrace();
    			}			
    
    //			The procedure extracts data from the EXTRACT_CCLNS table and outputs it to a file.          			
    			f_extract(user_id, year, DataName, dataset);
    //			The procedure deletes records from extract_cclns table after extracting the file.
    			f_delete(user_id);
    
    
    			return str+ "PROCESSING BEGAN";
    		}
    
    		private static void f_truncate() {
    			String SqlDel = ("DELETE FROM load.SCHOOLPAY"); 
    			int	Count_DeletedRows=0;
    			try {
    				[COLOR="red"]Count_DeletedRows = statement.executeUpdate(SqlDel);[/COLOR]----------------> and points to statement ...????? should statement and connection be declared in this class ,  
    			} catch (SQLException e) {                                             and i did that on the top
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			System.out.println("The number of times the Rows where deleted from the EXTRACT_CCLNS table: "+Count_DeletedRows);
    		}
    
    		private static void sequence() {
    			try{
    				//run the sequence procedure here .
    				CallableStatement proc_stmt =connection.prepareCall("{call load.P_RESET_SEQUENCE}");				            	
    				proc_stmt.executeQuery();
    			}catch (SQLException sqle){    								
    				System.err.println("\nSQLException:\n");
    				System.err.println("SQLState: "+sqle.getSQLState());
    				System.err.println("Message: "+ sqle.getMessage());
    			}
    		}
    
    }

    Error i got is :-
    ---------------------

    Exception in thread "main" java.lang.NullPointerException
    at school.payExtraction.sequence(payExtraction.java:1 57)
    at school.payExtraction.process(payExtraction.java:86 )
    at school.MainClass.main(MainClass.java:60)

    I have marked all the error lines in RED .

    Need help in completing and running it successfully.

    Thank You .

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  11. #11
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Sorry, but that's too much non-compilable code. I wouldn't know where to begin.

    Much luck
    If you notice,

    private static Connection connection;
    private static Statement statement;

    These 2 statements , r their in both the classes . MainClass and payExtraction class.

    public static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static String DATABASE_URL;

    These 2 lines r their only in MAINCLASS.

    I feel these errors , i mentioned r related to the way , the above lines are written .

    Can you pls look at them and guide me ....
    i feel from payExtraction class , it is not getting connected to the database .

    But i dont know , how to give the connection to oracle.

    Should i declare the above 4 lines in both the classes.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please avoid use of non-standard abbreviations. It takes quite a bit of effort to understand complex questions such as yours, and these abbreviations only make it harder. Also, many of the volunteers here don't speak English as a primary or secondary language, and non-standard abbreviations make it extremely difficult on them.

    Thanks.

    As to your problem, you are calling a method on a non-initialized static variable, payExtraction.statement, so it should come as no surprise that this will throw a NPE.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I don't do database programming, but I think you need to decide which class(es) will be responsible for database access or for initiating the database - the main/menu class or the two application classes. My guess would be the latter, but I can't say for sure. If so, then each needs to be able to initiate database contact and make all calls to the database. If it's the main class, then you may need to pass a reference to the database into your two application classes.

  14. #14
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Please avoid use of non-standard abbreviations. It takes quite a bit of effort to understand complex questions such as yours, and these abbreviations only make it harder. Also, many of the volunteers here don't speak English as a primary or secondary language, and non-standard abbreviations make it extremely difficult on them.

    Thanks.

    As to your problem, you are calling a method on a non-initialized static variable, payExtraction.statement, so it should come as no surprise that this will throw a NPE.
    Pls tell me what to write , so that the error doesnot occur ..

    I am learning .

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by renu View Post
    Pls tell me what to write , so that the error doesnot occur ..

    I am learning .
    I gave some suggestions above your post, but again, I am no database expert, so I can't help you with that portion. Also, we try to leave writing of code to you, but again if you need to use a Statement object from the main class in one of your application classes, then again, pass it into the other class via a method or constructor parameter.

    Luck.

  16. #16
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    I gave some suggestions above your post, but again, I am no database expert, so I can't help you with that portion. Also, we try to leave writing of code to you, but again if you need to use a Statement object from the main class in one of your application classes, then again, pass it into the other class via a method or constructor parameter.

    Luck.
    I tried all day , and cameback to ask and verify what you told

    Can you pls give me an example to explain how to pass the statement object into the other class (here dataExtraction class ) via a method or constructor parameter.

    Your answer is of grt help to me .

  17. #17
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,945
    Rep Power
    19

    Default

    OK.
    It's a start.

    For the db stuff, now I'm not sure what your table structure is so this is not really going to be a perfect answer from me...but...shift all db access into it's own class for the time being. That way you can have methods that do stuff to the db. Normally this would be one or more Data Access Objects, each one related to an entity in your system. Now, I cannot make out any entities, so it's possible this is just some sort of procedural thing you've got here...I don't know.

    The methods inside that db class will get a connection (a fresh one each time), create a statement (a fresh one each time), execute and close the connection and statement in finally blocks (each close wrapped in a try/catch). You could hold onto a single connection for the entire run, but for now I'd simply have a method that returns a new connection which you can then close. Another reason for this is that most db interaction will take this form anyway (getConnection, create/prepareStatement, execute, close), so may as well get used to it.

    This will help in isolating your db stuff, which should help in tidying up your code. Do that and we can then get back to the rest of it.

  18. #18
    renu is offline Senior Member
    Join Date
    May 2010
    Posts
    117
    Rep Power
    0

    Question Invalid User ID and Password in a console program should allow user to reenter them.

    I wrote a dbconnection method , where the database connection is obtained by passing uerid and password got from 2 methods written to extract user id and password.
    When the database connection fails because of wrong user id or passsword, the program now gives a message

    After that it should gain prompt for the user id and password , till it achieves the connection to database.
    How to achieve this part ...any help is appreciated .


    Quote Originally Posted by renu View Post
    Hi

    I had to write a java application , which contains code to run either one of the application from choice of 2 application.

    I am trying my best to explain , so that someone can help me , write a better java code.

    In real world example ,
    say their is a school project :-
    having a choice to run
    1)pay roll for teachers
    2)fees for students
    And it is a console application

    choice 1 entered , it runs pay roll for teachers .

    My application is similar to the real world example.

    I wrote everything in one class.But now i want to create 2 classes , one for 1)choice one application (from above example ..it is running just the pay roll for teachers .
    second for 2)choice two application
    (from above example ..just running fees for students.

    Can anyone help me in writing 3 different classes.
    I am posting my code here ...


    MAINCLASS :-

    Java Code:
    package school;
    
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintStream;
    import java.io.Writer;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.Scanner;
    
    import oracle.jdbc.driver.OracleTypes;
    
    public class MainClass {
    
    	static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    
    //	Global Variable : 
    	public static String DATABASE_URL;
    	public static int Count_DeletedRows;
    	public static int outputCount = 0;
    	public static String pathOfFile;
    	private static Connection connection;
    	private static Statement statement;
    	 
    //	Global Variable : Six Output Files 
    	public static String AuditFile1;
    	public static String AuditFile2;
    	public static String OutputFile;
    	public static String DCNVOutput;
    	
    	public static void main(String[] args) throws ClassNotFoundException {
    
    //		Local Variables :
    		int yrfrom;
    		int yrto;
    		int lnfrom;
    		int lnto;
    		int recCount = 0;
    
    		String DBServer = System.getProperty("DBServer","DEV");
    		System.out.println("server is " +DBServer);
    		if(DBServer.equals("QA")){
    			System.out.println("Entered the QA area");
    			DATABASE_URL =" jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ....";
    		}else if(DBServer.equals("PROD")){
    			System.out.println("The default is PROD");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = .....";
    		}else {
    			System.out.println("Entered the DEV area");
    			DATABASE_URL ="jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ......";
    		}
    
    		pathOfFile = System.getenv("TEMP");
    		Scanner scan = new Scanner(System.in); 
    		System.out.println("Please enter desired task number:");
    		System.out.println("1 =Pay roll for teachers");
    		System.out.println("2 =fees for students");
    		int enteredVal = scan.nextInt();
    
    		if (enteredVal==1)
    		{
    			Class1 class1 = new Class1();
    			String process = class1.process("PAY ROLL INFORMATION");
    			System.out.println("process :"+process);
    
    //			Calling the procedure to enter all the input values required.
    			String user_id = f_userid(scan);	
    			String password = f_password(scan);
    			dbConnect(user_id, password);
    			int year = f_year(scan);
    			int DataName = f_dataName(scan);
    			int dataset = f_dataSet(scan); 
    //			Here we enter the input filename with fully qualified path
    			try {
    				File readin = null;                                                                          
    				boolean gettingFilename = true;
    			while(gettingFilename) {
    					System.out.println("Enter fully qualified file name: ");
    					String inFile = scan.next();					
    					readin = new File(inFile);
    					if(readin.exists()){
    						System.out.println("All Parameters are entered by User ");
    						Filename myHomePage = new Filename(inFile, '\\', '.');
    						String Filename = myHomePage.filename(); 
    						OutputFile = pathOfFile + "\\EXTRACT_" + Filename + ".tsv";
    						System.out.println("The output file is located at:"+OutputFile);
    						AuditFile1 = pathOfFile + "\\Audit_" + Filename + ".txt";
    						System.out.println("The Audit file is located at:"+AuditFile1);
    
    						gettingFilename = false;						 
    					}else{                                                                                                                                              
    						System.out.println("File Not Found");
    					}			 
    				}	
    
    //				The results of all System.out.println's are captured in this Audit file.
    				try {					
    					System.setOut(new PrintStream(new FileOutputStream(new File(AuditFile1),false)));
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    				}
    
    //				Truncate the EXTRACT_CCLNS table before processing
    				f_truncate();
    //				Reset the sequence to 1.
    				sequence();				
    
    //				FIRST STEP	: Here I open the input file and read in record by record 
    				Scanner in = new Scanner(readin);
    				while (in.hasNextLine()){
    					String input = in.nextLine();
    					recCount++;		
    					String[] column = input.split(",");
    					int columnCount = column.length;				
    					if(columnCount == 4){
    //						the String to integer conversion happens here for each field of the record read.
    						yrfrom = Integer.parseInt(column[0].trim());
    						yrto = Integer.parseInt(column[1].trim());
    						lnfrom = Integer.parseInt(column[2].trim());
    						lnto = Integer.parseInt(column[3].trim());
    
    //						First IF statement B = A	
    						if(yrto == yrfrom){
    							//1 .BEGIN 
    							if(lnto == lnfrom){								
    //								Executing the procedure.								
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);				
    							}else if(lnto > lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);	
    							}else{
    								System.out.println("The LNTO IS LESSTHAN THE LNFROM : SO NO PROCESSING OF THIS RECORD");
    							}
    						}else if(yrto > yrfrom){
    							//2.BEGIN
    							if(lnto == lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);										
    							}else if(lnto > lnfrom){
    								f_dbInsert(yrfrom, yrto, lnfrom, lnto,user_id);												
    							}else{
    								System.out.println("The LNTO IS LESSTHAN THE LNFROM : SO NO PROCESSING OF THIS RECORD");
    							}						
    						}else{
    							System.out.println("THE YRTO IS LESSTHAN THE YRFROM : SO NO PROCESSING OF THIS RECORD");
    						}
    					}else{
    						System.out.println("THE INPUT FILE HAS COLUMN SIZE GREATER THAN 4 FOR THIS RECORD");
    					}
    				}
    			}catch(FileNotFoundException e){
    				e.printStackTrace();
    			}			
    
    
    		}else if (enteredVal==2)
    		{  			
    			Class2 class2 = new Class2();
    			String process = class2.process("FEES FOR STUDENTS");
    			System.out.println("process :"+process);	
    
    			scan = new Scanner(System.in);  
    //			Calling the procedures to get the input values .
    			String user_id = f_userid(scan);	
    			String password = f_password(scan);
    			dbConnect(user_id, password);
    			int year = f_year(scan);
    			int DataName = f_dataName(scan);
    			
    
    //			The path of the Output file 
    			FEESOutput = pathOfFile + "\\FEES_COMPARE.csv"; 
    			
    //			The results of all System.out.println's are captured in this Audit file.
    			try {					
    				System.setOut(new PrintStream(new FileOutputStream(new File(AuditFile2),false)));
    			} catch (FileNotFoundException e) {
    				e.printStackTrace();
    			}		
    //			Calling the procedure which gives us an output file for fees compare.
    			f_feescompare(year,.....);			
    		} else {
    			System.err.println("EXIT THE PROGRAM AND RUN AGAIN");
    			System.exit(1);
    		}	
    	}
    
    	[COLOR="Red"]private static void dbConnect(String user_id, String password){
    		try {
    			Class.forName(JDBC_DRIVER);	
    			connection = DriverManager.getConnection(DATABASE_URL,user_id,password);
    			connection.setAutoCommit(false);
    			statement = connection.createStatement();
    		} catch (SQLException e) {
    			String temp = e.getMessage();
    			temp = temp.replaceAll(temp, "Login Error: improper username and/or password! /n");
    			System.err.println("ERROR MESSAGE IS:"+temp);
    			System.exit(1);
    		} catch (ClassNotFoundException e) {
    			System.err.println("Database URL Not Found! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}[/COLOR]	private static void dbClose() {
    		try {
    			statement.close();
    			connection.close();
    			System.exit(1);
    		}catch (SQLException e){
    			System.err.println(" Error Closing Database Connection! \n" + e.getMessage());
    			System.exit(1);
    		}
    	}
    	private static void f_truncate() {
    		String SqlDel = ("DELETE FROM ......"); 
    		try {
    			Count_DeletedRows = statement.executeUpdate(SqlDel);
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    	}
    	
    	
           private static int f_year(Scanner scan) {
    		Calendar cal = new GregorianCalendar();
    		int years = cal.get(Calendar.YEAR); 
    		System.out.println("Enter the 4 digit year: ");
    		int year = scan.nextInt();  //Scan the input
    		while(year< 2004 || year > years){
    			System.out.println("Invalid Year.Year cannot be lessthan 2004 and greaterthan current year");
    			System.out.println("Enter the 4 digit year:");
    			year = scan.nextInt();
    		}
    		return year;
    	}
    	[COLOR="red"]private static String f_password(Scanner scan) {
    //		char[] paswd=System.console().readPassword("Enter password:");
    ////		Thread.currentThread();
    ////		Thread.sleep(1);
    //		String password = new String(paswd);
    //		System.out.println("The value of the password got from the console is:"+password);
    //		-----
    		System.out.println("Enter password: ");
    		String password = scan.next();  //Scan the input 
    		return password;
    	}[/COLOR]	[COLOR="red"]private static String f_userid(Scanner scan) {
    		System.out.println("Enter user id: ");
    		String user_id = scan.next();  //Scan the input 
    		int userlen = user_id.length();
    		while(userlen != 5){	
    			System.out.println("The user id is less than 5 characters long .PLEASE ENTER RIGHT USER ID ");
    			System.out.println("Please enter userid again of 5 characters length: ");
    			user_id = scan.next();  //Scan the input 
    			userlen = user_id.length();
    		}
    		return user_id;
    	}[/COLOR]	private static void f_extract(String user_id, int year, int DataName,int dataset) {		
    /		CallableStatement proc_stmt;		
    
    		try {	
    			FileOutputStream fos;	
    			fos = new FileOutputStream(new File(OutputFile),false);
    			Writer out = new OutputStreamWriter(new BufferedOutputStream(fos));
    			proc_stmt = connection.prepareCall("{? = call F_CREATE_HEADER(?)}");	
    //			Register the type of the return value		
    			proc_stmt.registerOutParameter(1,OracleTypes.VARCHAR);			   
    			proc_stmt.setString(2,user_id);
    //			Execute and retrieve the returned value
    			// Execute and retrieve the returned value
    			proc_stmt.execute();
    			String  retValue = proc_stmt.getString(1);
    			out.write(retValue);
    			out.write("\r\n");
    			proc_stmt.close();
    
    //			Call a function with four IN parameter; the function returns a VARCHAR
    			proc_stmt = connection.prepareCall("{? = call F_MAIN(?,?,?,?)}");
    			// Register the type of the return value
    			proc_stmt.registerOutParameter(1,OracleTypes.CURSOR);		   
    			proc_stmt.setString(2,user_id);
    			proc_stmt.setInt(3,DataName);
    			proc_stmt.setInt(4,year);
    			proc_stmt.setInt(5,dataset);
    			// Execute and retrieve the returned value
    			proc_stmt.execute();
    			ResultSet rs = (ResultSet) proc_stmt.getObject(1); // So, here it works. 
    			//print the results
    			int count = 0;
    			int ncols = rs.getMetaData().getColumnCount();
    
    //			for (int i=1; i<(ncols+1); i++) {
    //			out.append(rs.getMetaData().getColumnName(i));
    //			if (i<ncols){ 
    //			out.append(",");
    //			}else{
    //			out.append("\r\n");
    //			}
    //			}
    			while (rs.next()) {
    				count++;
    				for (int i=1; i<(ncols+1); i++) {
    					out.append(rs.getString(i));
    					if (i<ncols){
    						out.append(",");
    					} else{ out.append("\r\n");
    					}
    				}	
    			}
    			System.out.println("THE NUMBER OF RECORDS IN THE OUTPUT FILE ARE:"+count);
    			proc_stmt.close();
    			out.flush();
    			out.close();
    		}catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	private static void sequence() {
    		try{
    			//run the sequence procedure here .
    			CallableStatement proc_stmt = connection.prepareCall("{call P_RESET_SEQUENCE}");				            	
    			proc_stmt.executeQuery();
    		}catch (SQLException sqle){    								
    			System.err.println("\nSQLException:\n");
    			System.err.println("SQLState: "+sqle.getSQLState());
    			System.err.println("Message: "+ sqle.getMessage());
    		}
    	}
    	private static void f_dbInsert(int yrfrom, int yrto, int lnfrom, int lnto,
    			String user_id) {
    		try {
    		
    			CallableStatement proc_stmt = connection.prepareCall("{call P_INSERTMORE_PROC(?,?,?,?,?)}");
    			proc_stmt.setString(1,user_id);
    			proc_stmt.setInt(2,yrfrom);
    			proc_stmt.setInt(3,yrto);
    			proc_stmt.setInt(4,lnfrom);
    			proc_stmt.setInt(5, lnto);
    			proc_stmt.executeQuery();
    			proc_stmt.close();
    		}catch (SQLException sqle){    								
    			System.err.println("\nSQLException:\n");
    			System.err.println("SQLState: "+sqle.getSQLState());
    			System.err.println("Message: "+ sqle.getMessage());
    		}
    	}
    	
    	public static void f_feecompare(int year,......){
    			
    		// Call a function with two IN parameters; the function returns a cursor
    		CallableStatement proc_stmt = null;
    
    		try {
    			FileOutputStream fos;					
    			fos = new FileOutputStream(new File(DCNVOutput));					
    			Writer out = new OutputStreamWriter(new BufferedOutputStream(fos));		
    			proc_stmt = connection.prepareCall("{? = call F_CREATE_HEADER}");
    //			Register the type of return value
    			proc_stmt.registerOutParameter(1,OracleTypes.VARCHAR);
    //			Execute and retrieve the returned value
    			proc_stmt.execute();
    			String retValue = proc_stmt.getString(1);
    			out.write(retValue);
    			out.write("\r\n");
    //			Call a function with seven IN parameters; the function returns a cursor.
    			proc_stmt = connection.prepareCall("{? = call F_2_IDS(?,?,?,?,?,?,?)}");	
    //			Register the type of the return value		
    			proc_stmt.registerOutParameter(1,OracleTypes.CURSOR);			   
    			proc_stmt.setInt(2,year);
    			proc_stmt.setString(3,facilityname);
    			proc_stmt.setInt(4, DataName);
    			proc_stmt.setString(5, fee1);
    			proc_stmt.setString(6, version1);
    			proc_stmt.setString(7, fee2);
    			proc_stmt.setString(8, version2);			
    //			Execute and retrieve the returned value
    			proc_stmt.execute();
    			ResultSet rs = (ResultSet) proc_stmt.getObject(1); // So, here it works. 
    			//print the results
    			int count = 0;
    			int ncols = rs.getMetaData().getColumnCount();
    
    			while (rs.next()) {
    				count++;
    				for (int i=1; i<(ncols+1); i++) {
    					out.append(rs.getString(i));
    					if (i<ncols){
    						out.append(",");
    					} else{ out.append("\r\n");
    					}
    				}	
    			}
    			System.out.println("THE NUMBER OF RECORDS IN THE OUTPUT FILE ARE:"+count);
    			proc_stmt.close();
    			out.flush();
    			out.close();
    		}catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			System.out.println(e.toString());
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    			System.out.println(e.toString());
    		} catch (SQLException e) {
    			String temp = e.getMessage();
    			temp = temp.replaceAll(temp, "A ID COULD NOT BE LOCATED ..BECAUSE OF WRONG INPUTS");
    			System.err.println("ERROR MESSAGE IS:"+temp);
    		} 
    	}
    
    }
    CLASS1 :-
    Java Code:
    public class Class1 {
    	
    
    	public String process(String str)
    	{
    		
    		return str+ "PROCESSING BEGAN";
    	}
    	
    }
    cAN ANYONE ..tell me , what to include in the Class1 class from MAINCLASS class .

    so that main class looks simplier..then having all code at one place.

    I am learning object oriented programming ..

    need help ..in writing this project.

    All the code is their in MAINCLASS.

    Thanks in advance .
    Last edited by renu; 10-26-2010 at 07:01 PM.

  19. #19
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by renu View Post
    I am learning object oriented programming ..
    Then start at the beginning: start by writing down, in plain English, what you want to accomplish; not too much detail and no Java code, I repeat: no Java code yet. If you have done that mark all the nouns in your little story. The nouns are probably going to be your classes. Next mark all the verbs in your little story; those are probably going to be the methods in your classes.

    Next group all your verbs (methods) per noun (class) and check whether or not one (or some) of your classes have too many methods. You probably have too many sentences with 'it' and 'and' in them. Rewrite your little story until you're satisfied.

    The next step is the 'collaboration' step; visualize your nouns (classes) as blobs that can do something (the verbs). Those classes have to work together (the collaboration part). Imagine it's a little theatre piece where each class plays a role. Of course if class A wants class B to do something it has to know about that class B. If one (or more) classes need to know about too many other classes go all the way back to step one and rewrite your little story.

    Now that you know what your classes are going to be and with what classes they have to collaborate appoint responsibilities to them. A database class should be responsible for, indeed, the database and shouldn't have anything to do with asking passwords from the user or displaying data on the screen. If a (or some) classes have too many responsibilites it's back the drawing board again: go back to step one and rewrite your little story.

    Now that you have your classes, the responsiblities and collaboration all set up you have finished the CRC game. Only then it's time to start coding. Before that leave that stupid computer alone and play the game.

    I'd like to add a few rules of thumb of mine:

    a) No class should be longer than a few pages on paper.
    b) No method should be longer than a single page on screen.
    c) You should be able to describe what a method does in one short sentence.
    d) You should be able to describe what a certain class is for in one sentence without the word 'and' in it.

    kind regards,

    Jos
    Last edited by JosAH; 10-26-2010 at 08:02 PM.

Similar Threads

  1. is java is pure object oriented program?
    By 435.mahesh in forum New To Java
    Replies: 1
    Last Post: 04-21-2009, 03:42 PM
  2. Object Oriented
    By GraemeH in forum New To Java
    Replies: 3
    Last Post: 03-29-2009, 07:50 PM
  3. Object- Oriented guide?
    By sciguy77 in forum New To Java
    Replies: 4
    Last Post: 01-18-2009, 03:33 AM
  4. Is JAVA completely object-oriented???
    By venkateshk in forum New To Java
    Replies: 2
    Last Post: 11-17-2008, 09:17 AM
  5. Question about java object oriented Language
    By lenny in forum New To Java
    Replies: 3
    Last Post: 07-26-2007, 03:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •