Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Trying to out.println of random selected record

  1. #1
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Trying to out.println of random selected record

    Hello this program is supposed to read the data of a specified .txt file which it does then it promts you to pick a specfic line of data from that .txt file it compiles fine but will not write data on screen of selected data

     
    import java.nio.file.*;
    import java.io.*;
    import java.nio.file.attribute.*;
    import static java.nio.file.StandardOpenOption.*;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.util.Scanner;
    public class ReadStateFile
    {
    	public static void main(String[] args)
    	{
    		Scanner kb = new Scanner(System.in);
    		String fileName;
    		System.out.print("Enter name of file to use >> ");
    		fileName = kb.nextLine();
    		fileName = fileName;
    		Path file = Paths.get(fileName);
    		final String ID_FORMAT = "000";
    		final String NAME_FORMAT = "          ";
    		final int NAME_LENGTH = NAME_FORMAT.length();
    		final String HOME_STATE = "WI";
    		final String BALANCE_FORMAT = "0000.00";
    		String delimiter = ",";
    		String s = ID_FORMAT + delimiter + NAME_FORMAT + delimiter + HOME_STATE + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
    		final int RECSIZE = s.length();
    		byte data[] = s.getBytes();
    		final String EMPTY_ACCT = "000";
    		String[] array = new String[4];
    		double balance;
    		double total = 0;
    	try
    	{
    		BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
    		System.out.println("\nAttributes of the file:");
    		System.out.println("Creation time " + attr.creationTime());
    		System.out.println("Size " + attr.size());
    	}
    	catch(IOException e)
    	{
    		System.out.println("IO Exception");
    	}
    	try
    	{
    		InputStream iStream = Files.newInputStream(file, READ);
    		BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
    		System.out.println("\nAll non-default records:\n");
    		s = reader.readLine();
    		while(s != null)
    		{
    			array = s.split(delimiter);
    			if(!array[0].equals(EMPTY_ACCT))
    			{
    				balance = Double.parseDouble(array[3]);
    				System.out.println("ID #" + array[0] + " " + array[1] + array [2] + " $" + array[3]);
    				total += balance;
    			}
    			s = reader.readLine();
    		}
    		System.out.println("Total of all balances is $" + total);
    		reader.close();
    	}
    	catch(Exception e)
    	{
    		System.out.println("Message: " + e);
    	}
    	try
    	{
    		FileChannel fc = (FileChannel)Files.newByteChannel(file, READ, WRITE);
    		ByteBuffer buffer = ByteBuffer.wrap(data);
    		int findAcct;
    		System.out.print("\nEnter acount to seek >> ");
    		findAcct = kb.nextInt();
    		fc.position(findAcct * RECSIZE);
    		fc.read(buffer);
    		s = new String(data);
    		System.out.println("Desired record: " + s);
    	}
    	catch(Exception e)
    	{
    		System.out.println("Message: " + e);
    	}
    	}
    }

    first request looks like this in jGRASP


    Enter name of file to use >> InStateCusts.txt

    Attributes of the file:
    Creation time 2012-11-10T18:57:35.21Z
    Size 32000

    All non-default records:

    ID #101 Franklin WI $1034.38
    ID #104 Samuels WI $0100.99
    Total of all balances is $1135.37


    Enter acount to seek >> 101

    \\ heres where it goes wrong its supposed to repeat the requested data and i get

    Desired record: ,WI,0000.00
    00

    any help would be appericated!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    Could you post a copy of the input file for testing?
    Last edited by Norm; November 12th, 2012 at 03:39 PM. Reason: problem fixed
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    Im taking a class called intro to computer programming

    to compile it our teacher has us using jGRASP latest version and the book we are using is Java Programming Sixth Edition by Joyce Farrell

     
    import java.nio.file.*;
    import java.io.*;
    import java.nio.channels.FileChannel;
    import java.nio.ByteBuffer;
    import static java.nio.file.StandardOpenOption.*;
    import java.util.Scanner;
    import java.text.*;
    public class CreateFilesBasedOnState
    {
    	public static void main(String[] args)
    	{
    		Scanner input = new Scanner(System.in);
    		Path inStateFile = 
    			Paths.get("InStateCusts.txt");
    		Path outOfStateFile = 
    			Paths.get("OutOfStateCusts.txt");
    		final String ID_FORMAT = "000";
    		final String NAME_FORMAT = "               ";
    		final int NAME_LENGTH = NAME_FORMAT.length();
    		final String HOME_STATE = "WI";
    		final String BALANCE_FORMAT = "0000.00";
    		String delimiter = ",";
    		String s = ID_FORMAT + delimiter + NAME_FORMAT + delimiter + HOME_STATE + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
    		final int RECSIZE = s.length();
    		FileChannel fcIn = null;
    		FileChannel fcOut = null;
    		String idString;
    		int id;
    		String name;
    		String state;
    		double balance;
    		final String QUIT = "999";
     
    		createEmptyFile(inStateFile,s);
    		createEmptyFile(outOfStateFile,s);
     
    		try
    		{
    			fcIn = (FileChannel)Files.newByteChannel(inStateFile,CREATE, READ, WRITE);
    			fcOut = (FileChannel)Files.newByteChannel(outOfStateFile,CREATE, READ, WRITE);
    			System.out.print("Enter customer account number >>");
    			idString = input.nextLine();
    			while(!(idString.equals(QUIT)))
    			{
    				id = Integer.parseInt(idString);
    				System.out.print("Enter name for customer >>");
    				name = input.nextLine();
    				StringBuilder sb = new StringBuilder(name);
    				sb.setLength(NAME_LENGTH);
    				name = sb.toString();
    				System.out.print("Enter state >>");
    				state = input.nextLine();
    				System.out.print("Enter balance >>");
    				balance = input.nextDouble();
    				input.nextLine();
    				DecimalFormat df = new DecimalFormat(BALANCE_FORMAT);
    				s = idString + delimiter + name + delimiter + state + delimiter + 
    					df.format(balance) + System.getProperty("line.separator");
    				byte data[] = s.getBytes();
    				ByteBuffer buffer = ByteBuffer.wrap(data);
    				if(state.equals(HOME_STATE))
    				{
    					fcIn.position(id*RECSIZE);
    					fcIn.write(buffer);
    				}
    				else
    				{
    					fcOut.position(id*RECSIZE);
    					fcOut.write(buffer);
    				}
    				System.out.print("Eneter next customer account number or " + QUIT + " to quit >>");
    				idString = input.nextLine();
    			}
    				fcIn.close();
    				fcOut.close();
    			}
    		catch(Exception e)
    		{
    			System.out.println("Error message:" + e);
    		}
    	}
    	public static void createEmptyFile(Path file,String s)
    	{
    		final int NUMRECS = 1000;
    		try
    		{
    			OutputStream outputStr = Files.newOutputStream(file, CREATE);
    			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStr));
    			for(int count = 0; count < NUMRECS; ++count)
    				writer.write(s, 0, s.length());
    			writer.close();
    		}
    		catch(Exception e)
    		{
    			System.out.println("Error message:" + e);
    		}
     
    	}
    }

    this is the input program i have the file location set to default which is same location as where the program is saved, this was a You Do It assignment right out of the book but we found that the book has some syntex errors as far as: OutputSteam commands in the book it was

    OutputStream outputStr = new BufferedOutputStream(file.newOutputStream(CREATE)) ;

    and the proper updated syntex is

    OutputStream outputStr = Files.newOutputStream(file, CREATE);

    so im wondering if there might be a problem in the FileChannel Position if statement

    fcIn.position(findAcct * RECSIZE);

    but i cant see the problem but as far as i can tell when you go to select the specific file by typeing in the ID # its not properly locating it.


    thanks again for repling

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    Problem fixed, see below.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    Yes sir as of right now it compiles and runs fine using jGRASP the problem is its not recalling the selected file properly as far as your errors go maybe you compiler is using the same syntax from the book when I get home from work ill post the code that is right out of the book. The ones that I had to change because jGRASP did not like the syntax

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    I can't compile the code for testing because of the errors I posted. I am using the javac command that comes with the SDK for java 1.7 to compile the code.

    I have no idea what compiler JGrasp uses for compiling.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    After we downloaded jGRASP the teacher also instructed us to download JDK 7 and JRE from oracles website of that helps

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    I just downloaded the java 1.7 SDK two days ago.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    Ya I reinstalled them the day I posted the question I'm not sure the problem I know that another student uses notepad ++ to write the code and then uses the command line to compile and run the program and he had an issue where it wasn't compiling durning command line but when he opened jGRASP it compiled fine maybe this is the same thing?

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    I found my error. A previous question had a class named: Files that was being picked up. Renamed it out of the way and now both classes you posted compile without errors.

    How do I test the program?
    Last edited by Norm; November 12th, 2012 at 03:38 PM. Reason: Found the problem
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    First run the the class CreateFileBasedOnState input a few data the after your done exit program with 999 then it should create the two files in the folder you designated then run the sec program ReadStateFile your prompted to enter file name if your using same names you enter either InStateCusts.txt or OutOfStateCusts.txt make sure you add the .txt it wouldn't work if I didn't then the program should bring up the data you entered the prompt you to choose a file by entering the ID # and its supposed to repeat that file back to you but mine doesn't

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    For easier testing, define the Scanner object with the needed input for testing instead of requiring the tester to type in data. For example:
      Scanner input = new Scanner("the input here\nanother line\n999\n");
    Then the code will execute without the user being required to do anything
    AND everyone will be testing with the same input.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    I kinda understand but we were not required to use a scanner the program was designed for user input so ID numbers are rand three digits a name up to ten characters long two digit state abrv. And then balance which is 0000.00 we defined in program but I guess if I'm doing scanner right it would be something like this

     
    Scanner input = new Scanner("213\nWalters\nAZ\n1234.88\n");
    Scanner input = new Scanner("104\nSamuels\nWI\n44.44\n");
    Scanner input = new Scanner("106\nDavis\nWI\n234.54\n");
    Scanner input = new Scanner("215\nJohnsonville\nFL\n1034.69\n999\n");

    If I'm understanding this right you should have four sets of data two will be placed into the out of state file and two into the in state file as WI is defined in program as in state Walters and Johnsonville should be placed in the out of state but as I said before the data is user defined there was no set norm.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    There should only be one definition for the Scanner object. For easy testing it should contain all the responses that will be read in the program when the next methods are called.
    Can you merge all responses into a single String in on Scanner object? Then this one line in the code can be replaced with the definition with all the responses:
    Scanner input = new Scanner(System.in);


    I modified your definition for input, executed the program and get two files written. They both contain many lines of this:
    000, ,WI,0000.00
    000, ,WI,0000.00
    000, ,WI,0000.00
    000, ,WI,0000.00
    000, ,WI,0000.00
    000, ,WI,0000.00
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    The lines that you are getting in the file are correct and they are in order so if you used ID# 102 you would have to scroll down to the 102nd line of that data.

    As far as the scanner data it is outside of my scope of understanding to be able to provide you with the appropriate line of coding.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    Some more suggestions for testing:
    Have the output files be small enough that it can easily be visually verified. 32K is too big
    Have a max of 30 lines.
    Add a toString() method to the Student class that returns: name, id, grades
    Print out the contents of the students ArrayList every time you add lots of data to it.

    When the testing is successful, the limits can be changed back.

    Here is the definition of Scanner I am using:
          Scanner input = new Scanner("213\nWalters\nAZ\n1234.88\n"+"104\nSamuels\nWI\n44.44\n"
                                     +"106\nDavis\nWI\n234.54\n"+"215\nJohnsonville\nFL\n1034.69\n999\n");
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Nov 2012
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trying to out.println of random selected record

    Ok I'll give it a try when I get home where you able to get the data to display when the sec program prompted you to enter the account you seek

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to out.println of random selected record

    The code has lots of bugs in it. I found them by adding lots of println statements that displayed the values of many of the program's variables as the code executed.
    I changed:
    		final int NUMRECS = 30; //1000;         //<<<<<<<<<<<<<<<<<<<<< too big
    and the record ids in the input to be in the range 1-30 so that the files created are workable.
    I looked at the output files in a hex editor to see what was written to the files.

    I made a few changes and get this output:
    Total of all balances is $278.98

    Enter acount to seek >> acct=15
    Desired record: 15,Samuels ,WI,0044.<
    The changes to the create program:
          Scanner input = new Scanner("2\nWalters\nAZ\n1234.88\n"+"15\nSamuels\nWI\n44.44\n"
                                     +"26\nDavis\nWI\n234.54\n"+"5\nJohnsonville\nFL\n1034.69\n999\n");
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. How I record sound using MIDI?
    By waseempki in forum Java SE APIs
    Replies: 4
    Last Post: September 16th, 2011, 02:16 PM
  2. Deleting record from database HELP! :(
    By shando1992 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 2nd, 2011, 12:36 AM
  3. how to delete record from checking checkbox value.
    By -_- in forum JavaServer Pages: JSP & JSTL
    Replies: 2
    Last Post: March 12th, 2010, 07:09 AM
  4. how to delete record based on checkbox selected checkbox
    By -_- in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: December 15th, 2009, 09:26 PM
  5. Jsp code which will enable to view a single row from the Database
    By hundu in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: July 5th, 2009, 07:56 AM

Tags for this Thread