Results 1 to 6 of 6
  1. #1
    downWithJava is offline Member
    Join Date
    Mar 2013
    Posts
    17
    Rep Power
    0

    Default passing from methods back to main.

    Hi guys this is pretty crap code, I just cant seem to improve at java. I have a a few methods and I want to pass a few items from the quotes method to the log file method so I can save the name and time in the text file. I cant seem to do it.. I also have a calculations method that I want to return a total but struggling at that to I know the variables in the calculations method does not work in the main because they are declared in that method. Some of the code here now is just me trying stuff. but is there anyway back from the rest of the mess
    Java Code:
    import java.util.Scanner;
    import java.io.*;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    
    public class sample {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		final int MAX_ENTRIES = 20;
    		final int MAX_SEATS = 56;
    		final String DELIMITER = "~";
    		String[] firstName = new String[MAX_ENTRIES];
    		String[] lastName = new String[MAX_ENTRIES];
    		String[] carReg = new String[MAX_ENTRIES];
    		String[] age = new String[MAX_ENTRIES];
    		String[] noOfTrips = new String[MAX_ENTRIES];
    		String[] dateOfTrip = new String[MAX_ENTRIES];
    		boolean[] penaltyPoints = new boolean[MAX_ENTRIES];
    		boolean[] fullLicenceHolder = new boolean[MAX_ENTRIES];
    		Scanner kb = new Scanner(System.in);
    		System.out.println("----------------------------------");
    		System.out.println("Welcome to uSaveCarInsurace.\n");
    		System.out.println("----------------------------------");
    		boolean exit = true;
    		while (exit) {
    			System.out.println("Would you like to get a Quote (y/n)");
    			String yesNo = kb.next();
    			if (yesNo.toLowerCase().charAt(0) == 'y') {
    
    				quote(kb, firstName, lastName, carReg, age, noOfTrips,
    						dateOfTrip, DELIMITER, penaltyPoints,fullLicenceHolder);
    
    			} else if (yesNo.toLowerCase().charAt(0) == 'n')
    				exit = false;
    			else
    				System.out.println("Invalid entry, try again...");
    		}
    		double totalCost=  calculations(numberOfPoints,inputAge,yearsWithLicence);
    		System.out.println();
    		// for (int i = 0; i < firstName.length; i++){
    		logFile(firstName, DELIMITER);
    		// }
    	}
    
    	public static void quote(Scanner kb, String[] firstName, String[] lastName,
    			String[] carReg, String[] age, String[] noOfTrips,
    			String[] dateOfTrip, String DELIMITER, boolean [] penaltyPoints,boolean[] fullLicenceHolder) {
    		String inputFirstName = "";
    		String inputLastName = "";
    		String inputCarReg = "";
    		int inputAge,numberOfPoints = 0;
    		String penaltyPointChoice = "";
    		String fullLicenceChoice = "";
    		try {
    
    			File customers = new File("QuoteDetails.txt");
    
    			if (!customers.exists()) {
    				customers.createNewFile();
    			}
    
    			FileWriter fWriter = new FileWriter(customers);
    			BufferedWriter bWriter = new BufferedWriter(fWriter);
    
    			do {
    				System.out.println("Please enter your First Name");
    				while (kb.hasNextInt() || kb.hasNextFloat()
    						|| kb.hasNextDouble()) {
    					kb.next();
    					System.out.println("Name must contain letters only.");
    				}
    				inputFirstName = kb.next();
    				for (int i = 0; i < firstName.length; i++){
    					firstName[i]+=inputFirstName;
    				}
    			} while (firstName.length == 0);
    
    			do {
    				System.out.println("\nPlease enter your Last Name");
    				while (kb.hasNextInt() || kb.hasNextFloat()
    						|| kb.hasNextDouble()) {
    					kb.next();
    					System.out.println("Name must contain letters only.");
    				}
    				inputLastName = kb.next();
    			} while (inputLastName.length() == 0);
    
    			do {
    				System.out
    				.println("\nPlease enter your car reg in format 98-c-1111");
    				while (kb.hasNextInt() || kb.hasNextFloat()
    						|| kb.hasNextDouble()) {
    					kb.nextLine();
    					System.out.println("please enter car reg.");
    				}
    				inputCarReg = kb.next();
    			} while (inputCarReg.isEmpty());
    			carType(kb, carReg, inputCarReg);
    			do {
    				System.out.println("\nPlease enter your age");
    				// while (kb.hasNextFloat() || kb.hasNextDouble()) {
    				// kb.nextLine();
    				// System.out.println("enter Age .");
    				// }
    				inputAge = kb.nextInt();
    			} while (inputAge <= 0 || inputAge > 90);
    
    			do {
    				System.out.println("Do you have penalty points?");
    				penaltyPointChoice=kb.next();
    				 //while (!penaltyPointChoice.equalsIgnoreCase("y") || !penaltyPointChoice.equalsIgnoreCase("n"));
    				if (penaltyPointChoice.equalsIgnoreCase("y")){
    					System.out.println("How many?");
    					numberOfPoints=kb.nextInt();
    				}
    			} while (penaltyPointChoice.isEmpty());
    				
    			System.out.println("Do you have a full licence?");
    			fullLicenceChoice=kb.next();
    			 //while (!penaltyPointChoice.equalsIgnoreCase("y") || !penaltyPointChoice.equalsIgnoreCase("n"));
    			if (fullLicenceChoice.equalsIgnoreCase("y")){
    				System.out.println("How many years?");
    				int yearsWithLicence=kb.nextInt();
    			}
    				bWriter.write(inputFirstName + DELIMITER + inputLastName
    						+ DELIMITER + inputCarReg + DELIMITER + inputAge);
    
    				bWriter.flush();
    				bWriter.close();
    
    			
    		}
    			catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    
    		public static void carType(Scanner kb, String[] carReg, String inputCarReg) {
    			String CarYear = "98";
    			String CarYear1 = "12";
    			String CarYear2 = "13";
    			String CarYear3 = "00";
    			String CarYear4 = "10";
    			if (inputCarReg.substring(0, 1).equals(CarYear.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Toyota Yaris");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear1.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Subaru Impreza");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear2.substring(0, 1))) {
    				System.out.println("\nThe car you want to insure is a Ford Focus");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear3.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Suzuki Swift");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear4.substring(0, 1))) {
    				System.out.println("\nThe car you want to insure is a Kia Rio");
    			} else {
    				System.out.println("\nThe car you want to insure is a Volvo S40");
    			}
    		}
    
    		public static double calculations(int numberOfPoints,int inputAge,int yearsWithLicence){
    			double flatPremium=500.50;
    				if (inputAge <=18 || inputAge <21){
    					flatPremium*=.75;
    					System.out.println(flatPremium);
    					if(numberOfPoints>4) {
    						
    						if(yearsWithLicence<1){
    					}
    					}
    				}
    				return flatPremium;
    		}
    		public static void logFile(String[] firstName, String DELIMITER) {
    			try {
    
    				File log = new File("Logfile.txt");
    
    				if (!log.exists()) {
    					log.createNewFile();
    				}
    				DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy/HH:mm:ss");
    				Date date = new Date();
    				FileWriter fWriter = new FileWriter(log);
    				BufferedWriter bWriter = new BufferedWriter(fWriter);
    
    				bWriter.write(firstName + DELIMITER + dateFormat.format(date));
    				bWriter.flush();
    				bWriter.close();
    
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    
    	}
    Last edited by downWithJava; 04-18-2013 at 07:27 PM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: passing from methods back to main.

    What result are you seeing?
    What should you be seeing?
    Include any exceptions and stack traces, or errors if this doesn't compile.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    335
    Rep Power
    4

    Default Re: passing from methods back to main.

    If a method is used to determine the value of the variables you are using you could call the methods with no parameters and ask it to return the values. Given the number of values you want to return this would probably require the use of an array which can get very messy given what you are trying to return.
    Alternatively make the variables global so they can be seen by all methods.

    Another alternative, and one I would recommend having a go at, would be creating a Customer or Details class to store all of the required information. This is a tidy way of doing this and as Java is an Object-Orientated language you will need to do this at some point. You could then either call the details from the object to put into the text file or store the object itself within a file. The latter would require the object to be Serializable which just requires an import statement and two additional words to implement the interface.

    Regards.

  4. #4
    downWithJava is offline Member
    Join Date
    Mar 2013
    Posts
    17
    Rep Power
    0

    Default Re: passing from methods back to main.

    Thanks not working with classes yet, just the methods so far. So wont have time to research... Have a look at this I made some changes (again a lot of this code is not great or intended for use in the way it is, its just me experimenting. My issue that i am trying to focus in on right now though, is see the method calculations I am trying to return that to the quotes method and then pass back that to the age array to the main. My problem is.. I have to initialize the variable inputAge so i set to = 0 But when I try run the program I input the age. But when I try it with the if statement in the calculations method it remains 0. Here is code:

    Java Code:
    import java.util.Scanner;
    import java.io.*;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    public class sample2{
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		final int MAX_AMOUNT = 20;
    		final String DELIMITER = "~";
    		String[] firstName = new String[MAX_AMOUNT ];
    		String[] lastName = new String[MAX_AMOUNT ];
    		String[] carReg = new String[MAX_AMOUNT ];
    		int[] age = new int[MAX_AMOUNT ];
    		double[] totalPremium = new double[MAX_AMOUNT ];
    		boolean[] penaltyPoints = new boolean[MAX_AMOUNT ];
    		boolean[] fullLicenceHolder = new boolean[MAX_AMOUNT ];
    		Scanner kb = new Scanner(System.in);
    		
    		
    		System.out.println("----------------------------------");
    		System.out.println("Welcome to uSaveCarInsurace.\n");
    		System.out.println("----------------------------------");
    		readFile(DELIMITER);
    		boolean exit = true;
    		
    		while (exit) {
    			System.out.println("Would you like to get a Quote (y/n)");
    			String yesNo = kb.next();
    			if (yesNo.toLowerCase().charAt(0) == 'y') {
    
    				quote(kb, firstName, lastName, carReg, age, totalPremium, DELIMITER, penaltyPoints,fullLicenceHolder);
    			//	String userIDA=
    			} else if (yesNo.toLowerCase().charAt(0) == 'n'){
    		
    				System.out.println("Good Bye");
    				exit = false;
    			}
    			else
    				System.out.println("Invalid entry, try again...");
    		}
    		
    		// for (int i = 0; i < firstName.length; i++){
    		logFile(firstName, DELIMITER);
    		// }
    	}
    
    	public static String quote(Scanner kb, String[] firstName, String[] lastName,
    			String[] carReg, int[] age, double[] totalPremium, String DELIMITER, boolean [] penaltyPoints,boolean[] fullLicenceHolder) {
    		String inputFirstName = "";
    		String inputLastName = "";
    		String inputCarReg = "";
    		int inputAge = 0,numberOfPoints = 0;
    		String penaltyPointChoice = "";
    		String fullLicenceChoice = "";
    		int counterIndex = 0;
    		try {
    
    			File customers = new File("QuoteDetails.txt");
    
    			if (!customers.exists()) {
    				customers.createNewFile();
    			}
    
    			FileWriter fWriter = new FileWriter(customers);
    			BufferedWriter bWriter = new BufferedWriter(fWriter);
    			FileReader fReader = new FileReader(customers);
    			BufferedReader bReader = new BufferedReader(fReader);
    			
    			//do {
    				String record = null;
    				while ((record = bReader.readLine()) != null) {
    				String[] fields = record.split(DELIMITER);
    				//boolean[] fields2 = record.split(DELIMITER);
    				
    				while ((record = bReader.readLine()) != null) {
    				firstName[counterIndex] = fields[0];
    				lastName[counterIndex] = fields[1];
    				carReg[counterIndex] = fields[2];
    				age[counterIndex] = Integer.parseInt(fields[3]);
    				fullLicenceHolder[counterIndex] = Boolean.parseBoolean(fields[4]);
    				penaltyPoints[counterIndex] = Boolean.parseBoolean(fields[5]);
    				counterIndex++;
    				}
    				}
    				firstName[counterIndex] = userFirstName( kb, inputFirstName);
    				lastName[counterIndex] = userLastName( kb, inputLastName);
    				carReg[counterIndex] = userCarReg( kb, inputCarReg);
    				age[counterIndex] = userAge( kb, inputAge);
    				totalPremium[counterIndex] =calculations(numberOfPoints,inputAge);
    			//}while (inputFirstName.isEmpty());
    			
    
    				do {
    					System.out.println("Do you have penalty points?");
    					penaltyPointChoice=kb.next();
    					 //while (!penaltyPointChoice.equalsIgnoreCase("y") || !penaltyPointChoice.equalsIgnoreCase("n"));
    					if (penaltyPointChoice.equalsIgnoreCase("y")){
    						System.out.println("How many?");
    						numberOfPoints=kb.nextInt();
    					}
    				} while (penaltyPointChoice.isEmpty());
    				
    				System.out.println("Do you have a full licence?");
    				fullLicenceChoice=kb.next();
    				 //while (!penaltyPointChoice.equalsIgnoreCase("y") || !penaltyPointChoice.equalsIgnoreCase("n"));
    				if (fullLicenceChoice.equalsIgnoreCase("y")){
    					System.out.println("How many years?");
    					int yearsWithLicence=kb.nextInt();
    				}
    			
    			
    			//carType(kb, carReg, inputCarReg);
    		
    				bWriter.write(inputFirstName + DELIMITER + inputLastName
    						+ DELIMITER + inputCarReg + DELIMITER );
    
    				bWriter.flush();
    				bWriter.close();
    
    			
    		}
    		catch (IOException e) {
    				e.printStackTrace();
    		}
    		return firstName[counterIndex];
    			
    	}
    		public static String userFirstName(Scanner kb, String inputFirstName){
    			System.out.println("Please enter your First Name");
    			while (kb.hasNextInt() || kb.hasNextFloat()
    					|| kb.hasNextDouble()) {
    				inputFirstName= kb.next();
    				System.out.println("Name must contain letters only.");
    			}
    			inputFirstName = kb.next();
    			return inputFirstName;
    		}
    		public static String userLastName(Scanner kb, String inputLastName){
    			do {
    				System.out.println("\nPlease enter your Last Name");
    				while (kb.hasNextInt() || kb.hasNextFloat()
    						|| kb.hasNextDouble()) {
    					kb.next();
    					System.out.println("Name must contain letters only.");
    				}
    				inputLastName = kb.next();
    			} while (inputLastName.length() == 0);
    			return inputLastName;
    		}
    		public static String userCarReg(Scanner kb, String inputCarReg){
    			do {
    				System.out
    				.println("\nPlease enter your car reg in format 98-");
    				while (kb.hasNextInt() || kb.hasNextFloat()
    						|| kb.hasNextDouble()) {
    					kb.nextLine();
    					System.out.println("please enter car reg.");
    				}
    				inputCarReg = kb.next();
    			} while (inputCarReg.isEmpty());
    			return inputCarReg;
    		}
    		public static int userAge(Scanner kb, int inputAge){
    			do {
    				System.out.println("\nPlease enter your age");
    				// while (kb.hasNextFloat() || kb.hasNextDouble()) {
    				// kb.nextLine();
    				// System.out.println("enter Age .");
    				// }
    				inputAge = kb.nextInt();
    			} while (inputAge <= 0 || inputAge > 90);
    			return inputAge;
    		}
    		
    		public static void carType(Scanner kb, String[] carReg, String inputCarReg) {
    			String CarYear = "98";
    			String CarYear1 = "12";
    			String CarYear2 = "13";
    			String CarYear3 = "00";
    			String CarYear4 = "10";
    			if (inputCarReg.substring(0, 1).equals(CarYear.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Toyota Yaris");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear1.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Subaru Impreza");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear2.substring(0, 1))) {
    				System.out.println("\nThe car you want to insure is a Ford Focus");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear3.substring(0, 1))) {
    				System.out
    				.println("\nThe car you want to insure is a Suzuki Swift");
    			} else if (inputCarReg.substring(0, 1).equals(CarYear4.substring(0, 1))) {
    				System.out.println("\nThe car you want to insure is a Kia Rio");
    			} else {
    				System.out.println("\nThe car you want to insure is a Volvo S40");
    			}
    		}
    
    		public static double calculations(int numberOfPoints,int inputAge){
    			double flatPremium=500.50;
    			System.out.println(inputAge);
    		
    				if (inputAge <21){
    					flatPremium+=700;
    					System.out.println(flatPremium);
    				//	if(numberOfPoints>4) {
    						
    					//	if(yearsWithLicence<1){
    					//}
    				//	}
    				}
    				else if (inputAge>=22 && inputAge <25){
    					flatPremium+=200;
    					System.out.println(flatPremium);
    					if(numberOfPoints>4) {
    						
    					//	if(yearsWithLicence<1){
    					//}
    					}
    				}
    				return flatPremium;
    		}
    		public static void logFile(String[] firstName, String DELIMITER) {
    			try {
    
    				File log = new File("Logfile.txt");
    
    				if (!log.exists()) {
    					log.createNewFile();
    				}
    				DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy/HH:mm:ss");
    				Date date = new Date();
    				FileWriter fWriter = new FileWriter(log);
    				BufferedWriter bWriter = new BufferedWriter(fWriter);
    
    				bWriter.write(firstName + DELIMITER + dateFormat.format(date));
    				bWriter.flush();
    				bWriter.close();
    
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		public static void readFile(String DELIMITER){
    			
    		
    					
    					try {
    						File f = new File("QuoteDetails.txt");
    						FileReader fr = new FileReader(f);
    						BufferedReader br = new BufferedReader(fr);
    						
    						String record = null;
    						while ((record = br.readLine()) != null) {
    							String[] fields = record.split(DELIMITER);
    							System.out.print("Name: " + fields[0] + "\tScore: " + fields[1]);
    							System.out.println();
    						}
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    					
    				}
    
    			
    		}

  5. #5
    downWithJava is offline Member
    Join Date
    Mar 2013
    Posts
    17
    Rep Power
    0

    Default Re: passing from methods back to main.

    Ok I have resolved this by doing this in the quotes
    Java Code:
    age[counterIndex] = userAge( kb);
    int usersAge= age[counterIndex];
    AND adjusting the variable in the calculations method to usersAge. Is this the right way or is there a better approach.

  6. #6
    Ronin is offline Senior Member
    Join Date
    Oct 2010
    Posts
    335
    Rep Power
    4

    Default Re: passing from methods back to main.

    totalPremium[counterIndex] =calculations(numberOfPoints,age[counterIndex]);

    You can also put your declaration of kb onto line 10. This would allow kb to be used by all of the methods so you do not need to pass the scanner to every method.

    Regards.

Similar Threads

  1. Help passing arrays to other methods
    By arfor in forum New To Java
    Replies: 1
    Last Post: 02-03-2013, 09:59 PM
  2. Use of passing arguments in main method
    By REICHKONIG in forum New To Java
    Replies: 1
    Last Post: 01-01-2013, 04:50 PM
  3. Passing variables to methods
    By KKorn429 in forum New To Java
    Replies: 3
    Last Post: 05-21-2012, 12:40 AM
  4. Replies: 5
    Last Post: 04-02-2012, 07:52 AM
  5. passing arguments to other methods
    By popeyito18 in forum New To Java
    Replies: 2
    Last Post: 07-02-2011, 11:01 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
  •