The Artima Developer Community
Sponsored Link

Java Answers Forum
Writting to a text pad file...

6 replies on 1 page. Most recent reply: May 30, 2004 11:57 AM by Charles Bell

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 6 replies on 1 page
james

Posts: 3
Nickname: bobet
Registered: May, 2004

Writting to a text pad file... Posted: May 27, 2004 10:18 AM
Reply to this message Reply
Advertisement
Hi im trying to get a part of my java code to write to a text file. Ive tried every thing and for the life of me I cant get it to compile. Could some one help me plz?

//import librays
import java.io.*;
import java.util.*;
class prof2
{
	public static int genNumber()
	{
		//make me a random number generator called 'generator'
		Random generator = new Random();
		return generator.nextInt(9)+1;
	}
 
	public static void customer()
	{
		//Declaire Variables
		String surname, address;	//customers surname and address
		char initial, answer = 'y';;	//customers initial
		int account1, account2, account3, account4, account5;	//5 independant numbers
 
		System.out.println("**************************************************\n*****     Create a New Customer Account      *****\n**************************************************\n");
		System.out.println("Please enter Surname:\n");
		surname = EasyIn.getString();
		System.out.println("\nPlease enter customers initial:\n");
		initial = EasyIn.getChar();
		System.out.println("Please enter the customers address:\n");
		address = EasyIn.getString();
 
		//generate first number
		account1 = genNumber();
 
		//generate second number
		do
			{
			account2 = genNumber();
 
		//carry on all the time this generates a duplicate number
			}
 
		while (account2 == account1);
 
		//generate third number
		do
			{
			account3 = genNumber();
 
		//carry on all the time this generates a duplicate number
			}
		while (account3 == account1 | account3 == account2);
 
		//generate fourth number
 
		do
			{
			account4 = genNumber();
 
		//carry on all the time this generates a duplicate number
			}
 
		while (account4 == account1 | account4 == account2 | account4 == account3);
 
		//generate fifth number
		do
			{
			account5 = genNumber();
 
		//carry on all the time this generates a duplicate number
			}
			while (account5 == account1 | account5 == account2 | account5 == account3 | account5 == account4);
 
		//output the resulting numbers
			System.out.println("\nThe new account number is:" + account1 + ""+ account2 + ""+ account3 + ""+ account4 + ""+ account5);
 
		//Output new account details
			System.out.println("New account details:\n");
			System.out.println( "Account Name: "+surname+ " "+initial+ "\nAccount address: " +address+ "\nAccount number: " + account1 + ""+ account2 + ""+ account3 + ""+ account4 + ""+ account5);
		}
 
	/*-------------------------------------------------------------------------------------------------

	HireCar Method:
	Created and Designed by Neil Wilkie.
	This method is designed to allow a customer to hire a car by searching the following: Model, Engine Size or Age
	**/
	public static void hireCar()
	{
		//decalre variables
		char repeatChar, rightFile;
		byte choice, repeatByte;
		String search1, search3;
		double search2;
 
		//Create String array of owned cars
 
		String[] OwnedCar;
		OwnedCar = new String [10];
 
		OwnedCar [0] = ("Vauxhall, Corsa, 1.3, GP 03 CBT, 8,123, 35, Y");
		OwnedCar [1] = ("Vauxhall, Agila, 1.2, AB 03 FTR, 10,045, 38, S");
		OwnedCar [2] = ("Vauxhall, Agila, 1.0, FT 01 YUT, 21,488, 40, N");
		OwnedCar [3] = ("Vauxhall, Astra, 1.6, RT 51 DRE, 15,032, 32, S");
		OwnedCar [4] = ("Vauxhall, Astra, 2.2, DR 51 KLP, 19,933, 25, Y");
		OwnedCar [5] = ("Ford, Fiesta, 1.0, GP 53 REW, 4,987, 40, Y");
		OwnedCar [6] = ("Ford, Fiesta, 1.3, SR 01 BHG, 19,997, 35, N");
		OwnedCar [7] = ("Ford, Mondeo, 1.6, WE 02 GTY, 17,342, 33, N");
		OwnedCar [8] = ("Ford, Mondeo, 2.0, QW 52 EWQ, 12,345, 25, Y");
		OwnedCar [9] = ("Ford, Orion, 1.8, SD 01 TYR, 24, 459, 28, N");
 
		//Ask user what they would like to do
		System.out.println("Welcome to the Hire a car section of Cars R Us. What would you like to do?\n");
 
		//Start the loop for this section
		do
			{
 
			System.out.println("1)Search for a car by model?\n\n2)Search for a car by engine size?\n\n3)Search for car by age?\n");
			choice = EasyIn.getByte();
 
		//option 1 model search selected
		if (choice == 1)
			{
			System.out.println("\nPlease enter the model of the car you are looking for:\n");
			search1 = EasyIn.getString();
			}
 
		//option 2 engine size search selected
		if (choice == 2)
			{
				System.out.println("\nPlease enter the engine size of the car you are looking for:\n");
				search2 = EasyIn.getDouble();
			}
 
		//option 3 age search selected
		if (choice == 3)
			{
				System.out.println("\nPlease enter the age of the car you are looking for:\n");
				search3 = EasyIn.getString();
			}
		do
			{
				//Read in whether to repeat program or not
				System.out.print("\nWould you like to carry out a search again? (y or n): ");
				repeatChar = EasyIn.getChar();
				switch (repeatChar)
					{
						case 'Y':
						case 'y': repeatByte = 1; break;
						case 'N':
						case 'n': repeatByte = 2; break;
						default: repeatByte = 0;
						System.out.println("Invalid input. You must enter either a 'y' or a 'n' (this is not case sensitive)\n"); break;
					}
 
					}
					while ((repeatByte <1 || (repeatByte >2))); //invalid character entered
 
 
			}
				while (repeatByte != 2); //character not 'n' or 'N'
 
 
	}
 
	/*---------------------------------------------------------------------------------------------

	BuyCar Method:
	This method allows the user to buy a car
	**/
	public static void buyCar()
	{
		System.out.println("Nope Doesnt work either!");
	}
 
	/*---------------------------------------------------------------------------------------------
	Return CarMethod:
	Created and Designed by Stuart Coates.
	This method is designed to allow customers to return a car
	**/
	public static void returnCar()
	{
 
		//declare variables
		final byte 	costPerDay 	= 30;
		final float costPerMile = 0.55f;
		final byte 	mpg 		= 26;
		final float costOfFuel 	= 3.5f;
		int daysHired;
		int milesDone;
		float totalCost;
		byte customerType;
		int accountNumber;
		System.out.println("**************************************************\n*****              Return a Car              *****\n**************************************************\n");
		System.out.println("Preparing the bill\n");
 
		//read in the number of days car hired for
		System.out.print("How many days has the customer had the car: ");
		daysHired = EasyIn.getInt();
 
		//read in the mileage done
		System.out.print("\nHow many miles has the car done during the hire period: ");
		milesDone = EasyIn.getInt();
 
		//calculate cost of hire - cost consists of 3 things: daily hire charge, mileage charge and cost of fuel used
		totalCost = (costPerDay * daysHired) + (costPerMile * milesDone) + (costOfFuel * milesDone/mpg);
 
		//Ask if the customer is a one off customer or a returning customer
		System.out.println("\nIs the customer a returning customer?\n1)Yes\n2)No\n");
		customerType = EasyIn.getByte();
 
		if (customerType ==1)
		System.out.println("Please Enter the customers Account number:");
		accountNumber = EasyIn.getInt();
		System.out.println("\nacc" +accountNumber+" Thank you. The account has been up dated");
		{
		   String s = "";
 
 
		   FileOutputStream account; // declare a file output object
		   PrintStream printstream; // declare a print stream object
 
		try
		{
		// Create a new customer stream
		account = new FileOutputStream("acc"+accountNumber+".txt");
 
		// Connect print stream to the output stream
 
		s = ("account");
		printstream = new PrintStream( account );
		printstream.println (s + " " + "Cars R Us Account Details");
		printstream.println ("\nAccount Number:"+accountNumber+);
		printstream.println ("\nThe total amount payable is:"+totalCost+);
		printstream.println ("\nThis bill covers a total of "+daysHired+ "hired");
		printstream.println ("\nWith a total milage of" +milesDone+" travelled");
		printstream.close();
		}
		catch (Exception e)
 
		{
		  System.err.println ("Error writing to file");
        }
 
 
		if (customerType ==2)
		System.out.println("\nCost of hire: " + totalCost);
 
	}
}
 
 
	/*---------------------------------------------------------------------------------------------
	The main method
	**/
 
 
 
	public static void main (String[]args)
	{
 
		{//decalare variables
		byte choice;
		char repeatChar;
 
		//Print out the options for the user
		System.out.println("**************************************************\n*****  Welcome to Cars R Us Car Hire system  *****\n**************************************************");
		System.out.println("\nFrom the list below please select your required function:");
		System.out.println("\n1)Hire a car;\n2)Return a car;\n3)Buy a car;\n4)Create a customer;\n\n");
		//caoture the users selection from the keyboard
		choice = EasyIn.getByte();
 
		/*
		This method "hireCar" was created and designed by Neil Wilkie"
		**/
		if(choice == 1)
		hireCar();
 
		else if (choice == 2)
		returnCar();
 
		else if (choice == 3)
		buyCar();
 
		/*
		The following "customer" method was created by Kieran Marshel.
		**/
		else if (choice == 4)
		customer();
 
		else
		System.out.println("Incorrect Selection!");
}
	}
}


Any help would be great!


Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Writting to a text pad file... Posted: May 28, 2004 2:07 AM
Reply to this message Reply
Could you post the code for the EasyIn class?

james

Posts: 3
Nickname: bobet
Registered: May, 2004

Re: Writting to a text pad file... Posted: May 28, 2004 10:31 AM
Reply to this message Reply
Easy In class ok this is it:

// EasyIn.java
 
import java.io.*;
 
public abstract class EasyIn
{
  static String s = new String();
  static byte[] b = new byte[512];
  static int bytesRead = 0;
 
  public static String getString()
  {
     boolean ok = false;
     while(!ok)
     {
        try
        {
           bytesRead = System.in.read(b);
           s = new String(b,0,bytesRead-1);
           s=s.trim();
           ok = true;
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
     }
	return s;
   }
 
   public static int getInt()
   {
      int i = 0;
      boolean ok = false;
      while(!ok)
      {
         try
         {
             bytesRead = System.in.read(b);
             s = new String(b,0,bytesRead-1);
               i = Integer.parseInt(s.trim());
             ok = true;
         }
         catch(NumberFormatException e)
         {
            System.out.println("Make sure you enter an integer");
         }
         catch(IOException e)
         {
             System.out.println(e.getMessage());
         }
     }
     return i;
 }
 
 public static byte getByte()
 {
     byte i = 0;
     boolean ok = false;
     while(!ok)
     {
        try
        {
            bytesRead = System.in.read(b);
            s = new String(b,0,bytesRead-1);
            i = Byte.parseByte(s.trim());
            ok = true;
        }
        catch(NumberFormatException e)
        {
            System.out.println("Make sure you enter a byte");
        }
        catch(IOException e)
        {
             System.out.println(e.getMessage());
        }
     }
     return i;
 }
 
 public static short getShort()
 {
     short i = 0;
     boolean ok = false;
     while(!ok)
     {
        try
        {
            bytesRead = System.in.read(b);
            s = new String(b,0,bytesRead-1);
            i = Short.parseShort(s.trim());
            ok = true;
        }
        catch(NumberFormatException e)
        {
            System.out.println("Make sure you enter a short integer");
        }
        catch(IOException e)
        {
             System.out.println(e.getMessage());
        }
     }
     return i;
 }
 
 
 public static long getLong()
 {
    long l = 0;
    boolean ok = false;
    while(!ok)
    {
       try
       {
           bytesRead = System.in.read(b);
             s = new String(b,0,bytesRead-1);
           l = Long.parseLong(s.trim());
           ok = true;
       }
       catch(NumberFormatException e)
       {
           System.out.println("Make surre you enter a long integer");
       }
 
       catch(IOException e)
       {
            System.out.println(e.getMessage());
       }
    }
    return l;
 }
 
 
 public static double getDouble()
 {
    double d = 0;
    boolean ok = false;
    while(!ok)
    {
        try
        {
             bytesRead = System.in.read(b);
             s = new String(b,0,bytesRead-1);
             d = (Double.valueOf(s.trim())).doubleValue();
             ok = true;
        }
        catch(NumberFormatException e)
        {
             System.out.println("Make sure you enter a decimal number");
        }
        catch(IOException e)
        {
           System.out.println(e.getMessage());
       }
    }
    return d;
 }
 
 public static float getFloat()
 {
     float f = 0;
     boolean ok = false;
     while(!ok)
     {
        try
        {
            bytesRead = System.in.read(b);
            s = new String(b,0,bytesRead-1);
            f = (Float.valueOf(s.trim())).floatValue();
            ok = true;
        }
        catch(NumberFormatException e)
        {
            System.out.println("Make sure you enter a decimal number");
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
     }
	return f;
  }
 
  public static char getChar()
  {
     char c = ' ';
     boolean ok = false;
     while(!ok)
     {
        try
        {
           bytesRead = System.in.read(b);
           s = new String(b,0,bytesRead-1);
           if(s.trim().length()!=1)
           {
             System.out.println("Make sure you enter a single character");
           }
           else
           {
                c = s.trim().charAt(0);
                ok = true;
           }
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
     }
     return c;
  }
 
 
  public static void pause()
  {
     boolean ok = false;
     while(!ok)
     {
         try
         {
             System.in.read(b);
             ok = true;
         }
         catch(IOException e)
         {
              System.out.println(e.getMessage());
         }
     }
  }
 
  public static void pause(String messageIn)
  {
     boolean ok = false;
     while(!ok)
     {
         try
         {
              System.out.print(messageIn);
              System.in.read(b);
              ok = true;
         }
         catch(IOException e)
        {
              System.out.println(e.getMessage());
        }
    }
  }
}

Any help and little improvements would be great. Can some one explain to me how I search an array full of strings? I cant work it out for the life of me. Any help will be great thank you

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Writting to a text pad file... Posted: May 29, 2004 1:47 AM
Reply to this message Reply
Ive started looking at your code. As a suggestion for searching throught the Strings: I would use a 2 dimensional array to hold the car data:

String[][] OwnedCar =
		{	
			{"Vauxhall", "Corsa", "1.3", "GP 03 CBT", "8","123", "35", "Y"},
			{"Vauxhall", "Agila", "1.2", "AB 03 FTR", "10", "045", "38", "S"},
			{"Vauxhall", "Agila", "1.0", "FT 01 YUT", "21","488", "40", "N"},
			{"Vauxhall", "Astra", "1.6", "RT 51 DRE", "15", "032", "32", "S"},
			{"Vauxhall", "Astra", "2.2", "DR 51 KLP", "19", "933", "25", "Y"},
			{"Ford", "Fiesta", "1.0", "GP 53 REW", "4", "987", "40", "Y"},
			{"Ford", "Fiesta", "1.3", "SR 01 BHG", "19", "997", "35", "N"},
			{"Ford", "Mondeo", "1.6", "WE 02 GTY", "17", "342", "33", "N"},
			{"Ford", "Mondeo", "2.0", "QW 52 EWQ", "12", "345", "25", "Y"},
			{"Ford", "Orion", "1.8", "SD 01 TYR", "24", "459", "28", "N"}
		};
 


then search througth the array like this:

for (int r = 0; r < OwnedCar.length; r++)
{
	if (OwnedCar[r][0] == //car looking for)
	{
		//then do whatever
	}
}


This would be an example of looking for the make of the car.

Philip Foulkes

Posts: 19
Nickname: frodo
Registered: May, 2004

Re: Writting to a text pad file... Posted: May 29, 2004 2:14 AM
Reply to this message Reply
Writing to file:

FileWriter fw = new FileWriter ("customers.dat");
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
 
outFile.println (/*Some String*/);
outFile.close();


Do you know about Object Serialization? It makes life alot easier if for example you wanted to store the customer info.

james

Posts: 3
Nickname: bobet
Registered: May, 2004

Re: Writting to a text pad file... Posted: May 29, 2004 10:12 AM
Reply to this message Reply
I think I need to research Java even more. Thanks for the help. I thought if using a 2D array but wasnt sure. Thanks Ill try the code you suggested.

Many thanks!

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: Writting to a text pad file... Posted: May 30, 2004 11:57 AM
Reply to this message Reply
To get your program to compile I had to make the following corrections:
printstream.println (s + " " + "Cars R Us Account Details");
//printstream.println ("\nAccount Number:"+accountNumber+);
printstream.println ("\nAccount Number:"+accountNumber);
//printstream.println ("\nThe total amount payable is:"+totalCost+);


generally when a file writer is not saving a file with the updated contents, it means the file writer stream was not closed due to an oversight in the code.

Class names normally have the first letter capitalized:
prof2 would normally be named Prof2

It is not a requirent.

The whole idea of object oriented programming is so you can replace the geekish String arrays you have:
String[] OwnedCar;
OwnedCar = new String [10];

OwnedCar [0] = ("Vauxhall, Corsa, 1.3, GP 03 CBT, 8,123, 35, Y");
OwnedCar [1] = ("Vauxhall, Agila, 1.2, AB 03 FTR, 10,045, 38, S");
OwnedCar [2] = ("Vauxhall, Agila, 1.0, FT 01 YUT, 21,488, 40, N");
OwnedCar [3] = ("Vauxhall, Astra, 1.6, RT 51 DRE, 15,032, 32, S");
OwnedCar [4] = ("Vauxhall, Astra, 2.2, DR 51 KLP, 19,933, 25, Y");
OwnedCar [5] = ("Ford, Fiesta, 1.0, GP 53 REW, 4,987, 40, Y");
OwnedCar [6] = ("Ford, Fiesta, 1.3, SR 01 BHG, 19,997, 35, N");
OwnedCar [7] = ("Ford, Mondeo, 1.6, WE 02 GTY, 17,342, 33, N");
OwnedCar [8] = ("Ford, Mondeo, 2.0, QW 52 EWQ, 12,345, 25, Y");
OwnedCar [9] = ("Ford, Orion, 1.8, SD 01 TYR, 24, 459, 28, N");

with a class that acts as a data holder and the fields can be given names that human readable so you can read the code and understand it.
You make your data holders private and use get and set public methods.

Check out Bill Venner's chapter on Object design at:
http://www.artima.com/objectsandjava/webuscript/ClassesObjects1.html


class OwnedCar {
     private String .... = "";
     private String .... = "";
     private String .... = "";
     private int .... = 0;
     private char .... = "Y";
 
 
     public OwnedCar(String .... ,String .... ,String .... , int.... , char...){
 
     }
 
     public String get...()
         return ...
     }
 
 
     public void set...(String ...)
         this.... = ...
     }
}
 

Flat View: This topic has 6 replies on 1 page
Topic: Displaying exponent value without carot symbol Previous Topic   Next Topic Topic: Help with Java Applet Needed

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use