Hi all,

I am currently revising for an exam which will cover all the basics of object-oriented programming, it was going quite well until I met Collection :) I have got two questions to which I have started writing answers to but got stuck...Could someone please have a look at what I have done so far and maybe provide me with a guideline how I can finish the code?

QUESTION 1 (implementing Map):

The following table shows model numbers and names of fountain pens.
Model number Model name
707 "Antares"
1001 "Bootes"
911 "Rigel"
1032 "Vega"
Such tables are implemented and managed by instances of a class called
PenCatalogue.
(i) The class PenCatalogue needs a single private instance variable called
penMap. Write the declaration for penMap, it should be declared to be of a
suitable interface type to hold an unsorted map with integer keys and string
values. [3]

MY ANSWER:

private Map<Integer, String> penMap;

(ii) Write a zero-argument constructor for PenCatalogue that initialises penMap
to an empty map. [3]

public PenCatalogue()
{
penMap = new HashMap<Integer, String>();
}

iii)
Write an instance method called fillUp() for the PenCatalogue class that
takes no arguments and returns no value. This method should simply enter
the five entries shown above into the map.

public void fillUp()
{
penMap.put<707, "Antares">;
penMap.put<1001, "Bootes">;
penMap.put<911, "Rigel">;
penMap.put<1032, "Vega">;
}

iv)Write a second instance method for the PenCatalogue class called
updateCatalogue() which takes no arguments and returns no value. This
method should work irrespective of how many entries might subsequently be
added to the map referenced by penMap. This method should iterate through
all of the map’s keys. Where the integer key has a value less than 1000, then
" – withdrawn" should be added to the associated map value (as illustrated
below).

Now this is where I struggle..I think I need to use the for loop somewhere here but I haven't found a similar question in our course books so I am not quite sure how to proceed.

Any help will be highly appreciated :) I am going trough all kinds of questions just in case they might come up in the exam so I might be having more questions :D

Many many thanks in advance

Magda

Take a look at the Map.keySet() method. It will return a Set of the keys in the map. A for-each on that Set will allow you to compare the key value easily and Map.put(key, value) will replace the value if key already exists in the map. You should be able to implement your method pretty easily with that info.

Also, on "iii", you may want to look at the enclosures you used around the method parameters. Do those look right for a method call?

You can make use of entryset() use to bring the scenorio:

Please find the below code which might solve your problem:

public void updateCatalogue() {

for (Map.Entry<Integer,String> entry : penMap.entrySet()) {
 if(entry.getKey()<1000){
    entry.setValue("– withdrawn");
 }
            System.out.println(entry.getValue());
}
}

Please find the below code which might solve your problem:

Giving the answer to the exam question does nothing to promote active thought on the problem. Hints and suggestions, rather than canned solutions, are more appropriate.

Thank you very much for your suggestion :) You are absolutely right, am not looking for the canned solutions. I was able to complete the code with your suggestion :D

Hi all,

Thanks for your help so far ! I hope you wont mind if I ask you for help again..Being brutally honest I must admit that I didnt study the later material of the course properly what now effects in huge lacks in my knowledge...:'( after the Map and other Collection interface, the Streams have been introduced. I understand the whole concept of using them but I really struggle when it comes up to writing the method. I will post what I have come up with but am aware there are a lot of mistakes. I would appreciate if someone could check it and point me to the right direction.(the class OUFileChooser has been provided by the university)

The question:
Consider the following method comment and header defined for a
hypothetical class called FrogIO.
/**
* Prompts the user for a pathname which is then used to create a File
* object. The method then attempts to open a stream on that file.
* The method then writes the details of the frogs held in the argument
* frogCollection to the stream in CSV format
*/
public static void saveStateOfFrogs1(Collection<Frog> frogCollection)
Write the code for this method. Your code must make use of the File and
FileWriter classes. To achieve full marks your solution should make
appropriate use of buffering, inform the user of any exceptions that might
occur, and include a finally statement to ensure that once opened the stream is closed.

public static void saveStateOfFrogs(Collection<Frog> frogCollection)
{

String pathname= OUFileChooser.getFilename();
File aFile = new File(pathname);
ObjectOutputStream oustream = null;

try
{
oustream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(aFile)));
for (Frog eachFrog : FrogCollection)
{
bufferedFileWriter.write(eachFrog + ",");
bufferedFileWriter.newLine();
}
catch (Exception anException)
{
System.out.println("Error " + anException);
}
finally
{
try
{
outstream.close();
}
catch (Exception anException)
{
System.out.prinln("Error " + anException);
}
}
}

Hi all,

Thanks for your help so far ! I hope you wont mind if I ask you for help again..Being brutally honest I must admit that I didnt study the later material of the course properly what now effects in huge lacks in my knowledge...:'( after the Map and other Collection interface, the Streams have been introduced. I understand the whole concept of using them but I really struggle when it comes up to writing the method. I will post what I have come up with but am aware there are a lot of mistakes. I would appreciate if someone could check it and point me to the right direction.(the class OUFileChooser has been provided by the university)

The question:
Consider the following method comment and header defined for a
hypothetical class called FrogIO.
/**
* Prompts the user for a pathname which is then used to create a File
* object. The method then attempts to open a stream on that file.
* The method then writes the details of the frogs held in the argument
* frogCollection to the stream in CSV format
*/

public static void saveStateOfFrogs1(Collection<Frog> frogCollection)
Write the code for this method. Your code must make use of the File and
FileWriter classes. To achieve full marks your solution should make
appropriate use of buffering, inform the user of any exceptions that might
occur, and include a finally statement to ensure that once opened the stream is closed.

public static void saveStateOfFrogs(Collection<Frog> frogCollection)
{

String pathname= OUFileChooser.getFilename();
File aFile = new File(pathname);
ObjectOutputStream oustream = null;

try
{
oustream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(aFile)));
for (Frog eachFrog : FrogCollection)
{
bufferedFileWriter.write(eachFrog + ",");
bufferedFileWriter.newLine();
}
catch (Exception anException)
{
System.out.println("Error " + anException);
}
finally
{
try
{
outstream.close();
}
catch (Exception anException)
{
System.out.prinln("Error " + anException);
}
}
}

CSV format means Comma Separated Values, which means the stream you're using will most likely be one that writes ASCII information to a .txt file.

Furthermore, in order to write code to request input from the user, you can simply open an inputstream that will collect information from the keyboard.

Consider the following example:

import java.io.*;

public class TextIn{

	public static void main(String[] args){
		String str = "";
		BufferedReader input = null;
		try{
			input = new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Please enter the extension to retrieve the information from");
			str = input.readLine(); //reads line from user
			System.out.println("You have entered...:");
			System.out.println(str);
			System.out.println("Attempting to search for the file...");
			input.close();
			input = new BufferedReader(new FileReader(str));

			while(input.ready())System.out.println(input.readLine()); //this is what reads each line in the file

		}//end try
		catch(FileNotFoundException e){
			System.out.println("Couldn't find the file!");
			System.out.println(e.getStackTrace());
			System.exit(1);
		}
		catch(IOException e){
			System.out.print("\nHad some problem...");
			System.out.println(e.getStackTrace());
			System.exit(1);
		}
		finally{
			try{
				input.close();
			}
			catch(Exception e){
				System.out.println(e);
			}

			System.out.println("Program ends...");
			System.exit(0);
		}
	}//end main
}//end class

Hopefully that helps.

Thank you for your resonse Alex! Unfortunately I still don't get it..:$ Would you be able to correct what I have written? Your solution just seems too complicated for me..Sorry:confused:

Then ask for explanation on the point that is confusing you rather than asking for direct corrections to your code. You are the one studying and if you actually want to learn the material then you need to make the effort to clarify the points that you are having problems with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.