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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 41

Thread: Reading txt

  1. #1
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Reading txt

    Hey.

    So i have been dealing with a couple of reading assignments as of recently. But i am stuck on the last one.
    It is not that i don't know how to read from a file or put things from a file into an array.
    But rather that i don't know of where to start.

    Here is the assignment :
    Start by creating a new subpackage named sort_cities inside your package YourLnuUserName_assign4 and save all .java files related to this exercise inside this package.
    Implement a program SortCities that reads an arbitrary number of city names and their zip codes from a text file. You can assume one city in each line and that each city name (String) and zip code (integer) is separated by a semi-colon( ; ). Create a class City that represents a city and create a city object for each city you read from the file. The City class should also implement the interface Comparable. Once you have read (and constructed) one City object for each line in the file you should print the cities in a sorted order based on their zip codes. An execution might look like this:

    Reading cities from file: C:\Temp\cities.dat
    Number of cities found: 7

    23642 Höllviken
    35243 Växjö
    51000 Jönköping
    72211 Västerås
    75242 Uppsala
    90325 Umeå
    96133 Boden

    Notice: We expect you to use one of the predefined sorting algorithms in the Java class library when sorting the cities.


    I have three classes so far. One called "City", "Comparable" which is the interface and "CityMain" that will access the "City".

    Any ideas of where i should start? Not used to interfaces but i know how they work.
    Thanks.

  2. #2
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    Comparable is not a class but an interface. That means you implement it for the City class to provide a way of comparing one City instance to another. When you implement an interface you need to provide the code for the method signatures specified in the interface declaration. Check out the Java tutorial in my signature on interfaces. Also check out the Java API for the comparable interface description.

    Regards,
    Jim

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

    Default Re: Reading txt

    how to read from a file or put things from a file into an array.
    Look at using the Scanner class's methods to read from the file.

    A problem with using an array is that the array must be defined large enough to hold all the data that will be read.
    An ArrayList would not have that problem.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by Norm View Post
    Look at using the Scanner class's methods to read from the file.

    A problem with using an array is that the array must be defined large enough to hold all the data that will be read.
    An ArrayList would not have that problem.
    Was not being specific enough when writing, but yes you are right.
    I often go for ArrayList when i know that i am dealing with objects as a whole rather than fixed things.
    Also i am used to BufferedReader rather than the scanner but i can try out the scanner too.


    Quote Originally Posted by jim829 View Post
    Comparable is not a class but an interface. That means you implement it for the City class to provide a way of comparing one City instance to another. When you implement an interface you need to provide the code for the method signatures specified in the interface declaration. Check out the Java tutorial in my signature on interfaces. Also check out the Java API for the comparable interface description.

    Regards,
    Jim
    Yeah i knew that part but wasn't specific enough here either. But will still look at the tutorials!

  5. #5
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    Here's one approach.

    1. Create a City class as described.
    2. Then populate an instance via the constructor with a city and zipcode.
    3. Override toString to print the city and zipcode or include a separate method do do that.

    Once you have that working, focus on reading in the file and creating an instance for each city/zipcode combination.
    Print them out to see if they work.

    Then implement the required interface.

    The point is break up the task into small pieces that you can complete, debug, and then forget about. It makes things much easier.

    Regards,
    Jim

  6. #6
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by jim829 View Post
    Here's one approach.

    1. Create a City class as described.
    2. Then populate an instance via the constructor with a city and zipcode.
    3. Override toString to print the city and zipcode or include a separate method do do that.

    Once you have that working, focus on reading in the file and creating an instance for each city/zipcode combination.
    Print them out to see if they work.

    Then implement the required interface.

    The point is break up the task into small pieces that you can complete, debug, and then forget about. It makes things much easier.

    Regards,
    Jim
    Hey.

    Been doing it like you said but have gotten into a problem.
    I have sorted the integer array but now i need to sort the string
    array in the same way as i sorter the integer array.

    Not done yet and need to fix something, but if the sorting gets done then maybe there
    won't be too much left to do.

    This is how i've tried to sort the string arraylist as i did with the integer arraylist :
    	public void Sort() {
    		TreeMap tm = new TreeMap<Integer, String>();
    		Object[] arr = itemArr.toArray();
    		Object[] arr2 = descArr.toArray(null);
    		for (int i = 0; i < arr.length; i++) {
    			tm.put(arr2[i], arr[i]);
    		}
    		for (Object k : arr2) {
    			System.out.println(k);
    		}
     
    	}

    This is just one method from the "City" class. I will handle one thing at the time.

  7. #7
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    Why are you using a TreeMap? That is not necessary to sort a list of items. The assignment says,

    Notice: We expect you to use one of the predefined sorting algorithms in the Java class library when sorting the cities.

    Did you check out Arrays.sort or Collections.sort?

    Regards,
    Jim

  8. #8
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by jim829 View Post
    Why are you using a TreeMap? That is not necessary to sort a list of items. The assignment says,

    Notice: We expect you to use one of the predefined sorting algorithms in the Java class library when sorting the cities.

    Did you check out Arrays.sort or Collections.sort?

    Regards,
    Jim
    Yes... i did an "Collections.sort(numArr);"
    And it works fine...
    But did TreeMap because i thought that making that would change the order of the other array
    to the same order as the integer array.

  9. #9
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    Are you saying you have two arrays? If so, why?

  10. #10
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by jim829 View Post
    Are you saying you have two arrays? If so, why?
    Well i couldn't save it into one array with the mix of string and integers. Not saying that it cannot be done but just saying that i had to split them due to the semicolon.

    public void read() {
     
    		try {
    			FileReader file = new FileReader("C:\\Users\\pc\\Desktop\\BB.dat");
    			BufferedReader r = new BufferedReader(file);
    			String currLine;
    			while ((currLine = r.readLine()) != null) {
    				if (currLine.trim().length() > 0) {
    					String[] split = currLine.split(";");
    					itemArr.add(Integer.parseInt(split[0]));
    					descArr.add(split[1]);
    				}
    			}
    		} catch (IOException e) {
     
    		}
     
    	}

  11. #11
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    I think you missed the point of the assignment. My take was to create a City class and put the name and the zipcode as fields in that class. The class should implement the Comparable interface so you can then sort the class on the zipcode. You do not need two arrays to do that.

    Note also that you can set the delimiter in the Scanner class and then use the appropriate Scanner methods to get the values so you don't have to split the line. But your way of doing that also works.

    Regards,
    Jim

  12. #12
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by jim829 View Post
    I think you missed the point of the assignment. My take was to create a City class and put the name and the zipcode as fields in that class. The class should implement the Comparable interface so you can then sort the class on the zipcode. You do not need two arrays to do that.

    Note also that you can set the delimiter in the Scanner class and then use the appropriate Scanner methods to get the values so you don't have to split the line. But your way of doing that also works.

    Regards,
    Jim
    I see.. i am not that good of a reader and i often do get things mixed up.
    This is how i did it. This is the city class. Do note that the methods for the ArrayLists are
    rather pointless... the interger array does get sorter in one of them but that's still rather pointless
    because it could've been done just as easily in the "read" field. But i felt like i needed something for
    both lists.



    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.TreeMap;
     
    public class Ort implements Comparable {
    	public ArrayList<Integer> itemArr = new ArrayList<Integer>();
    	public ArrayList<String> descArr = new ArrayList<String>();
     
    	public void read() {
     
    		try {
    			FileReader file = new FileReader("C:\\Users\\me\\Desktop\\somefile.dat");
    			BufferedReader r = new BufferedReader(file);
    			String currLine;
    			while ((currLine = r.readLine()) != null) {
    				if (currLine.trim().length() > 0) {
    					String[] split = currLine.split(";");
    					itemArr.add(Integer.parseInt(split[0]));
    					descArr.add(split[1]);
    				}
    			}
    		} catch (IOException e) {
     
    		}
     
    	}
     
    	public ArrayList<String> cityName(ArrayList<String> l) {
    		descArr = l;
    		return l;
    	}
     
    	public ArrayList<Integer> zipC(ArrayList<Integer> l) {
    		Collections.sort(itemArr);
    		itemArr = l;
    		return l;
    	}
     
    	public void Sort() {
    		TreeMap tm = new TreeMap<Integer, String>();
    		Object[] arr = itemArr.toArray();
    		Object[] arr2 = descArr.toArray(null);
    		for (int i = 0; i < arr.length; i++) {
    			tm.put(arr2[i], arr[i]);
    		}
    		for (Object k : arr2) {
    			System.out.println(k);
    		}
     
    	}
     
    }





    Still stuck but i will take any help that i can get, thanks!

  13. #13
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    You have way too much stuff in there and most of it unnecessary. Just create a City class with two fields, an int zipcode field and a String name field. You can assign these via a constructor. Also include a toString method to return a String to print as described in the assignment. This class should be less than 20 lines of code.

    Regards,
    Jim

  14. #14
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by jim829 View Post
    You have way too much stuff in there and most of it unnecessary. Just create a City class with two fields, an int zipcode field and a String name field. You can assign these via a constructor. Also include a toString method to return a String to print as described in the assignment. This class should be less than 20 lines of code.

    Regards,
    Jim
    I see what you mean jim but why would i need a constructor? If i used a constructor then wouldn't i need to read the file from the main before even going into the city class?
    "Tick, tack"

  15. #15
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Reading txt

    The constructor is used to populate the class with certain values (also referred to as state). You read in the values of the file and while you do you create a City instance and place it in an a list.

    Assume you are in your MainClass and you have another class defined called City.

    while there is input from the scanner
         read zipcode
         read name
         City c = new City(name, zipcode)
         add c to list
    end

    Regards,
    Jim

  16. #16
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Okay so i think that i might be close now.

    However i have gotten into a problem.
    Cannot use constructors within the interface.
    I have tested without the interface all together and it works fine.

    Main :
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
     
    public class cityMain {
     
    	private static BufferedReader r;
     
    	public static void main(String[] args) {
    		int Z = 0;
    		String C = null;
    		try {
    			ArrayList<City2> City = new ArrayList<City2>();
     
    			FileReader file = new FileReader("C:\\Users\\me\\Desktop\\BB.dat");
    			r = new BufferedReader(file);
    			 String currLine;
    			while ((currLine = r.readLine()) != null) {
     
    				if (currLine.trim().length() > 0) {
    					String[] split = currLine.split(";");
    					Z = (Integer.parseInt(split[0]));
    					C = (split[1]);
    					City.add(new City2(Z, C));
    				}
    			}
    			Collections.sort(City, (c1, c2) -> c1.getZipCode() - c2.getZipCode());
     
    			for (int i = 0; i < City.size(); i++) {
    				System.out.println(City.get(i).getZipCode() + " " + City.get(i).getCityName());
     
    			}
     
    		} catch (IOException e) {
    			System.out.println("Erorr : " + e);
    		}
     
    	}
     
    }

    City :
    public class City2 implements Comparable {
     
    	private int zipCode;
    	private String cityName;
     
    	public City2(int zipCode, String cityName) {
    		this.zipCode = zipCode;
    		this.cityName = cityName;
    	}
     
    	public int getZipCode() {
    		return zipCode;
    	}
     
    	public String getCityName() {
    		return cityName;
    	}
     
    }

    And Comparable :
    public interface Comparable {
     
            City2(int zipCode, String cityName);    //<--- doesn't like this... 
     
     	public int getZipCode();
     
    	public String getCityName();
     
    }
    Ideas?
    "Tick, tack"

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

    Default Re: Reading txt

    You should not be defining the Comparable interface. That is already defined in the Java SE classes.
    When a class implements an interface, it needs to define the methods of the interface.
    Look at the API doc for Comparable to see what methods are required.
    http://docs.oracle.com/javase/8/docs/api/index.html
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by Norm View Post
    You should not be defining the Comparable interface. That is already defined in the Java SE classes.
    When a class implements an interface, it needs to define the methods of the interface.
    Look at the API doc for Comparable to see what methods are required.
    http://docs.oracle.com/javase/8/docs/api/index.html
    Well i thought that it was going so? "it need so define the methods of the interface" but its doing so?
    I am so lost haha.
    "Tick, tack"

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

    Default Re: Reading txt

    Take a look at the tutorial: https://docs.oracle.com/javase/tutor...interface.html

    Your code should use the definition of Comparable provided in the java SE classes. You should not define the interface yourself.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by Norm View Post
    Take a look at the tutorial: https://docs.oracle.com/javase/tutor...interface.html

    Your code should use the definition of Comparable provided in the java SE classes. You should not define the interface yourself.
    Looking in the classes i found "Comparable<T>", so you're saying... that i should use that in my interface?
    "Tick, tack"

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

    Default Re: Reading txt

    No. You do NOT define an interface. You are supposed to use the existing interface: Comparable.
    The tutorial at the link I posted has an example of how to use an interface.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #22
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by Norm View Post
    No. You do NOT define an interface. You are supposed to use the existing interface: Comparable.
    The tutorial at the link I posted has an example of how to use an interface.
    Okay so... the interface is like the "laws" that other classes has to follow. And the mainClass is calling another class throughout the deals of the interface.

    So from the mainClass it should look like this :
    TheInterface SomeName = new TheClassThatShouldBbeyTheLawsOfOurInterface "Aka the class name" ();
    And what i am doing is that i am calling the the class from the main directly... which i guess that i should not do.

    So i should call another class from mainClass throughout the Interface to the class that i want the Interfaces rules to apply.
    Hope i got that right...

    The the example is just an interface with a class, and the class has all the methods that the interface told the class to have.
    "Tick, tack"

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

    Default Re: Reading txt

    The Comparable interface defines a method that the sort method needs to be able to sort the collection of City objects. The sort method calls the interface's method to determine the ordering of two City objects.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #24
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Reading txt

    Quote Originally Posted by Norm View Post
    The Comparable interface defines a method that the sort method needs to be able to sort the collection of City objects. The sort method calls the interface's method to determine the ordering of two City objects.
    Sorry but i am still lost... haha.
    "Tick, tack"

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

    Default Re: Reading txt

    The tutorial shows an example. The Bicycle interface defines several methods. The ACMEBicycle class impletments that interface and provides definitions for the methods defined in the Bicycle interface. Now an instance of the ACMEBicycle class can be treated as a Bicycle allowing any other code to call any of the Bicycle interface's methods.

    For your case, the City class must implement the Comparable interface and provide definitions for the method(s) in Comparable. Then the sort method which requires objects of type Comparable will call the methods to sort a collection of City objects.
    Read the API doc for the Collections class's sort method. It says:
    All elements in the list must implement the Comparable interface.

    A commonly used interface is ActionListener. Have you used that? Look at the code for that.
    Also see an example in the tutorial:
    https://docs.oracle.com/javase/tutor...nlistener.html
    If you don't understand my answer, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. Reading lines from a txt file
    By neliJav in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 6th, 2013, 01:54 PM
  2. reading .txt files
    By deependeroracle in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: February 8th, 2012, 12:47 PM
  3. reading and witing to txt file
    By nautilusz in forum File I/O & Other I/O Streams
    Replies: 25
    Last Post: January 22nd, 2012, 02:02 PM
  4. [SOLVED] reading only certain lines from a .txt file
    By straw in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 7th, 2010, 07:49 PM
  5. Reading .txt and storing into an array
    By vluong in forum Collections and Generics
    Replies: 1
    Last Post: January 4th, 2010, 02:07 PM