Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Colonel Taint
Mar 14, 2004


yatagan posted:

Why do you think this? It's perfectly acceptable to check the types in a switch, and your interface pretty much demands it if you can't change that interface.

I'm not sure. It just goes against my intuition that it should be necessary for me to program a decision like that for every type of message receiver. Its likely just because I'm a bit lazy, and I haven't written anything substantial in Java in a long time.

Adbot
ADBOT LOVES YOU

PianoDragn
Jan 30, 2006
Edit: stupid mistake

PianoDragn fucked around with this message at 19:14 on Feb 26, 2010

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

SintaxError posted:

I'm not sure. It just goes against my intuition that it should be necessary for me to program a decision like that for every type of message receiver. Its likely just because I'm a bit lazy, and I haven't written anything substantial in Java in a long time.

The only thing I can think of to get around that without using metaprogramming is to have your abstract Message class define an abstract "onReceive()" method or something like that, and receiveMessage() just calls that.

You'd still have to code each one but at least it would be close to the message implementation.

Shavnir
Apr 5, 2005

A MAN'S DREAM CAN NEVER DIE

SintaxError posted:

I'm not sure. It just goes against my intuition that it should be necessary for me to program a decision like that for every type of message receiver. Its likely just because I'm a bit lazy, and I haven't written anything substantial in Java in a long time.

The issue is you don't have a good way of doing dynamic dispatch in Java. If your prof is the patterns-happy type you can use the visitor pattern to do that sort of behavior. Otherwise what you're doing works.

Glimm
Jul 27, 2005

Time is only gonna pass you by

In my Java class I am required to use FindBugs in all projects. I'm having trouble in my latest lab because I am getting a FindBug message "may fail to close stream" on the line I've commented below. Anybody point me in the direction to fix this problem?

code:
BufferedReader in = null;
try {
     in = new BufferedReader(new FileReader(filename)); //FindBugs error here
                   //do something with the file
   } catch (FileNotFoundException e) {
	System.out.println("Could not find file: " + filename);
	System.exit(-1);
   } catch (IOException e) {
	System.out.println("I/O Exception failure: " + filename + ": "
	+ e.getMessage());
	System.exit(-1);
   } finally {
	if (in != null) {
	try {
	     in.close();
	} catch (IOException e) {
		System.out.println("I/O Exception failure: " + filename
	        + ": " + e.getMessage());
		System.exit(-1);
	}
    }
}

ufarn
May 30, 2009
Any good information on how to create an ideal ETag for, say, a wiki article.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Glimm posted:

In my Java class I am required to use FindBugs in all projects. I'm having trouble in my latest lab because I am getting a FindBug message "may fail to close stream" on the line I've commented below. Anybody point me in the direction to fix this problem?

code:
BufferedReader in = null;
try {
     in = new BufferedReader(new FileReader(filename)); //FindBugs error here
                   //do something with the file
   } catch (FileNotFoundException e) {
	System.out.println("Could not find file: " + filename);
	System.exit(-1);
   } catch (IOException e) {
	System.out.println("I/O Exception failure: " + filename + ": "
	+ e.getMessage());
	System.exit(-1);
   } finally {
	if (in != null) {
	try {
	     in.close();
	} catch (IOException e) {
		System.out.println("I/O Exception failure: " + filename
	        + ": " + e.getMessage());
		System.exit(-1);
	}
    }
}

I don't personally have any experience with FindBugs, but "finally" blocks don't get executed if you call System.exit, so maybe that's why it's complaining? In a real world situation it probably doesn't matter too much, but as far as FindBugs is concerned, there are still paths in your code where "in.close()" never gets called.

Does the flag go away if you close your reader inside the catch clauses before you call System.exit?

Glimm
Jul 27, 2005

Time is only gonna pass you by

Flobbster posted:

I don't personally have any experience with FindBugs, but "finally" blocks don't get executed if you call System.exit, so maybe that's why it's complaining? In a real world situation it probably doesn't matter too much, but as far as FindBugs is concerned, there are still paths in your code where "in.close()" never gets called.

Does the flag go away if you close your reader inside the catch clauses before you call System.exit?

It doesn't go away - and CheckStyle tells me not to bother because in can only be null within those locations.

FindBugs is pretty neat - I find it helpful generally. Just wish I wouldn't lose points on my assignment for FindBug problems like the one I'm having right now!

RitualConfuser
Apr 22, 2008

Glimm posted:

In my Java class I am required to use FindBugs in all projects. I'm having trouble in my latest lab because I am getting a FindBug message "may fail to close stream" on the line I've commented below. Anybody point me in the direction to fix this problem?

code:
BufferedReader in = null;
try {
     in = new BufferedReader(new FileReader(filename)); //FindBugs error here
                   //do something with the file
   } catch (FileNotFoundException e) {
	System.out.println("Could not find file: " + filename);
	System.exit(-1);
   } catch (IOException e) {
	System.out.println("I/O Exception failure: " + filename + ": "
	+ e.getMessage());
	System.exit(-1);
   } finally {
	if (in != null) {
	try {
	     in.close();
	} catch (IOException e) {
		System.out.println("I/O Exception failure: " + filename
	        + ": " + e.getMessage());
		System.exit(-1);
	}
    }
}

Have you tried this:

code:
BufferedReader in = null;
try {
    try {
        in = new BufferedReader(new FileReader(filename));        
        //do something with the file
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                System.out.println("I/O Exception failure: " + filename
                        + ": " + e.getMessage());
                System.exit(-1);
            }
        }
    }
} catch (FileNotFoundException e) {
    System.out.println("Could not find file: " + filename);
    System.exit(-1);
} catch (IOException e) {
    System.out.println("I/O Exception failure: " + filename + ": "
            + e.getMessage());
    System.exit(-1);
}

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa
As FindBugs guys say themselves, FindBugs isn't a silver spoon but a great helper. In this particular case it's semantically correct as stated above, however if you're closing the VM then it just doesn't really matter if you close the stream or not.

I'd say that in cases like these it's important that you know what's going on and can explain to others (your teacher in this case) why you didn't get rid of that FindBugs error.

Out of curiosity, does the error go away if you do

code:
BufferedReader in = null;
FileReader fileReader = null;
try {
    fileReader = new FileReader(filename);
    in = new BufferedReader(fileReader);
} /* other code and catch blocks */ {
} finally {
    if (in != null) { try { in.close(); } catch (IOException e) {} }
    if (fileReader != null) { try { fileReader.close(); } catch (IOException e) {} }
}
I remember seeing FindBugs crap around a bit if you use multiple IO classes directly in constructors even though all IO classes are adapters with cascading behavior in close().

Glimm
Jul 27, 2005

Time is only gonna pass you by

Couldn't get it to go away with either of the above suggestions - I'll just take it to the prof and try to make sure I don't lose any points :) Thanks.

RitualConfuser
Apr 22, 2008
Slight modification:

code:
BufferedReader in = null;
try {
    try {
        in = new BufferedReader(new FileReader(filename));        
        //do something with the file
    } finally {
        if (in != null) {
            in.close();
        }
    }
} catch (FileNotFoundException e) {
    System.out.println("Could not find file: " + filename);
    System.exit(-1);
} catch (IOException e) {
    System.out.println("I/O Exception failure: " + filename + ": "
            + e.getMessage());
    System.exit(-1);
}

Also, which version of FindBugs are you using? I tried 1.3.9 and it doesn't find any errors with the original code.

E: I should have refreshed. Parantumaton is right though. If you can explain it I imagine your prof would be OK with it.

RitualConfuser fucked around with this message at 21:22 on Feb 27, 2010

Glimm
Jul 27, 2005

Time is only gonna pass you by

RitualConfuser posted:

Also, which version of FindBugs are you using? I tried 1.3.9 and it doesn't find any errors with the original code.

Weird, I'm using: 1.3.9.20090821 which appears to be the latest version?

RitualConfuser
Apr 22, 2008

Glimm posted:

Weird, I'm using: 1.3.9.20090821 which appears to be the latest version?

Odd.

You could try commenting out the "do something with the file" code and re-run FindBugs to see if that's where the problem is.

Glimm
Jul 27, 2005

Time is only gonna pass you by

RitualConfuser posted:

You could try commenting out the "do something with the file" code and re-run FindBugs to see if that's where the problem is.

Doh.. I have an error condition in there that calls System.exit without doing in.close, that fixed it.

covener
Jan 10, 2004

You know, for kids!

ufarn posted:

Any good information on how to create an ideal ETag for, say, a wiki article.

I would think the revision # alone would be a good strong etag.

karuna
Oct 3, 2006
I'm tying to cast an object to the same object but i'm getting a ClassCastException.

code:
Transport t = (Transport) in.readObject();
in.readObject() is a Transport object. Any idea's? Just doesn't make sense

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Try just Transport t ¿ in.readObject();

karuna
Oct 3, 2006

MEAT TREAT posted:

Try just Transport t ¿ in.readObject();

Doesn't seem to work?

Forgot to say, if it means anything, that Transport implements serializable

Fly
Nov 3, 2002

moral compass

karuna posted:

I'm tying to cast an object to the same object but i'm getting a ClassCastException.

code:
Transport t = (Transport) in.readObject();
in.readObject() is a Transport object. Any idea's? Just doesn't make sense
Why don't you print out the class that it really is to see what you're doing wrong? The ObjectInputStream does not think the next thing in the stream is a Transport object.

lamentable dustman
Apr 13, 2007

ðŸÂ†ðŸÂ†ðŸÂ†

Try printing out in.readObject().getClass().getName() and see what kind of object you actually are getting back

karuna
Oct 3, 2006
Transport - Used to wrap whatever I want to send accross. I am calling remote methods

code:

public class Transport implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	Class[] types;
	Object[] param;
	String name;
	
	public Transport(){
		
	}
}
code:
System.out.println(in.readObject().getClass().getName());
Returns "Client.Transport" so all seems ok here?

code:
public void run() {
		try{	
			ObjectInputStream in = new ObjectInputStream(this.socket.getInputStream());
			ObjectOutputStream out = new ObjectOutputStream(this.socket.getOutputStream());
			System.out.println("Something");
			
			//Transport t = (Transport) in.readObject(); 
			
			
			System.out.println(in.readObject().getClass().getName());
			//Do stuff
			//out.writeObject(scores);
			//out.flush();
			
			//close socket conn
			socket.close();
			out.close();
			in.close();
		}
		catch(IOException e){ System.out.println(e);}
		catch(ClassNotFoundException e){ System.out.println(e);}
	}

karuna fucked around with this message at 22:45 on Mar 1, 2010

Fly
Nov 3, 2002

moral compass

karuna posted:

Returns "Client.Transport" so all seems ok here?
Does System.out.println(Transport.class.getName()) print the same thing, or is it a different Transport class?

I think you'd get a different error were the serial version ids mismatched, but you might want to check that as well, but it should be okay if you're copying your class files.

Perhaps you're trying to load them from different ClassLoaders, and that is causing a problem.

karuna
Oct 3, 2006
I see what I've done wrong, I assumed I could just copy Transport in Client to Transport in Server.

System.out.println(Transport.class.getName())
returns Server.Transport

But I can just import the Transport class instead.

Import Client.Transport;

This seems to solve the problem

code:
Transport t = (Transport) in.readObject(); 

System.out.println(t.getName());
Returns, for this example, "print" which is the method I now need to call.

chippy
Aug 16, 2006

OK I DON'T GET IT
Could someone explain to me why the following line:

code:
exampleString = exampleString.replaceAll("\\t", "        ");
Is not doing what I expect it to (replace any tabs in a string with 5 spaces instead)? The tabs seem to be surviving intact.

yatagan
Aug 31, 2009

by Ozma

chippy posted:

Could someone explain to me why the following line:

code:
exampleString = exampleString.replaceAll("\\t", "        ");
Is not doing what I expect it to (replace any tabs in a string with 5 spaces instead)? The tabs seem to be surviving intact.

Works for me, are you sure you have tabs in your string?

chippy
Aug 16, 2006

OK I DON'T GET IT
Never mind, I'm a tool and had it in the wrong place :facepalm: Should have tested properly before I came running. Thankyou.

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


OK, so for this program for class, I need to make my own linked list and an iterator for that list. I am having trouble creating this iterator class . . . In Java, what IS an iterator? My linked list consists of these DoubleListnode<E> things that are doubly-linked nodes that you'd find in a linked list. This iterator class implements Iterator<E> but trying to just make an iterator doesn't really work. Would the iterator be some sort of <E> object? Or something else entirely? What would the constructor look like? I assume that it has to be set to point at the beginning of the list when it's constructed as well.

epswing
Nov 4, 2003

Soiled Meat
To "iterate" through a collection means to visit every element in a collection. You can iterate through the ints in an ArrayList<Integer>:
code:
for (int i = 0; i < myList.size(); i++) {
    Integer current = myList.get(i);
    // do something with current
}
Note that there's an easier way to do the same thing:
code:
for (Integer current : myList) {
    // do something with current
}
All collections give you a way to visit every element. There's a method to traverse a collection apart from the two methods above, which is to use an Iterator (which is what method 2 above does behind the scenes for you, I believe):
code:
Iterator<Integer> i = myList.iterator();
while (i.hasNext()) {
    Integer current = i.next();
    // do something with current
}
So you can picture the Iterator i starting out pointing to the first element in an ArrayList. i.hasNext() will be true, and i.next() will return the first element and move to the second, and so on. When you run out of elements, i.hasNext() will be false.

An ArrayList is backed by an array. You've got a linked list, so it's a different data structure underneath, but should be the same to work with. Start by pointing at the first element in the linked list, and i.hasNext() should return true and i.next() should return the first element and try to move to the second, and so on.

epswing fucked around with this message at 03:01 on Mar 4, 2010

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Specifically, Iterators must implement Iterator. To use a foreach loop on an object like epswing mentioned, that class must implement Iterable.

It's also worth noting that you can use the Java5 foreach construct to iterate over arrays as well as Iterable classes.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
I should add a note that there is nothing in the Iterator specification that says that you must return the same item order for the same collection every time. It could be completely different each time even though nothing's happened to the data since the last time. It just so happens that people count from 0 to the end of the list for arrays and lists, for example, and we're all used to arrays returning the same thing every time as a silent, implied convention. This idea breaks down when you get into hash tables and data structures that have several intuitive ways to travel through all the elements.

Revitalized
Sep 13, 2007

A free custom title is a free custom title

Lipstick Apathy
Okay, so here I'm suppose to make a simple program that will read from a file, and then make two more files (firstFile and secondFile). firstFile is suppose to be the input file, except in all uppercase. secondFile is suppose to be a compilation of all content of all the input files so far, also in uppercase.

Now, the first output works, I can consistently make a file with firstFile that gets overwritten each time I run the program, which is exactly what I want. However, it does not write into the second file. secondFile is created, but it remains empty, no matter how many times I run the program. What's wrong? I suspect I'm doing something wrong with FileWriter.

code:
	public static void main(String[]args) throws Exception
	{
		Scanner kb = new Scanner(System.in);
		System.out.print("Enter input filename: ");
		//Need an error message if file does not exist;
		String readFile = kb.nextLine();
		System.out.print("Enter output filename: ");
		String firstFile = kb.nextLine();
		System.out.print("Enter another output file: ");
		String secondFile = kb.nextLine();
		Scanner fOne = new Scanner(new File(readFile));
		
		PrintWriter outputFile = new PrintWriter(firstFile); //to modify first output
		FileWriter fwriter = new FileWriter(secondFile, true); //to modify second output

		while (fOne.hasNext())
		{
			outputFile.println(fOne.nextLine().toUpperCase());
		}
		outputFile.close();
		//go from input directly into output
		PrintWriter fileOutput = new PrintWriter(fwriter);
		while (fOne.hasNext())
		{
			fileOutput.println(fOne.nextLine().toUpperCase());
		}
		fileOutput.close();
	}
Also while I'm here, I forgot how to make an error message for if the inputfile doesn't exist. I keep reading online it's some try/catch thing, but I remember there was some other, simpler way to do it...

Thanks for any help

General Lee Awesome
Nov 8, 2009
Without giving a full blown solution:

In the first loop, you can actually do two things at once - write each line to first file in uppercase (which you are already doing, and will complete the first subtask), and write each line to the second file "as-is". This will be the first part of the second file task (Thats if i'm understanding your task correctly). Doing it in one loop is faster in this instance. To do this you will need to save the nextLine() as a String inside the loop and pass that in to println so you can use it more than once.

In the second loop, read from the first output file and write straight in to the second output file. This should give you a second duplicate block of text in that file, but in uppercase.

A few observations in your current code:

You are executing the same loop twice (in effect). If the first loop has already ended because fOne has no further lines, why would it loop at all the second time?

You also seem to be getting lost in writers wrapping writers. Use a separate writer for each file, and give them a better name (e.g "firstFileOutput" instead of "outputfile"). It will make your code easier to understand, not just for you but anyone else trying to use it. You can get clever with variables/instances when you have the basics down.

EDIT: I don't have JDK installed on this machine to check it, but this is how I would do it if I were to follow the style of your current code (i'm also assuming a little with regards to the classes you are using, having never had the need to use them before).

code:
                Scanner kb = new Scanner(System.in);

		System.out.print("Enter input filename: ");
		String readFile = kb.nextLine();

		System.out.print("Enter output filename: ");
		String firstFile = kb.nextLine();

		System.out.print("Enter another output file: ");
		String secondFile = kb.nextLine();

		Scanner inputFile = new Scanner(new File(readFile));

		PrintWriter firstFileOutput = new PrintWriter(firstFile);
		PrintWriter secondFileOutput = new PrintWriter(secondFile);

		while (inputFile.hasNext())
		{
                        // Store the line
                        String lineStr = inputFile.nextLine();

                        // Print it to first file as uppercase
			firstFileOutput.println(lineStr.toUpperCase());

                        // Print it to second file as normal
                        secondFileOutput.println(lineStr);
		}

                // Finished with the input file, close it.
		inputFile.close();

                // Completed writing the first file, close it.
                firstFileOutput.close();

                // Make a new scanner for the first output file
                Scanner uppercaseFile = new Scanner(new File(firstFile));

		while (uppercaseFile.hasNext())
		{
                        // Write each line from first file to second file
			secondFileOutput.println(uppercaseFile.nextLine());
		}

                // Close the second file.
                secondFileOutput.close();
I presume all that I/O will throw a possible IOException so you should wrap the lot in the try/catch statement to catch it.

General Lee Awesome fucked around with this message at 23:20 on Mar 4, 2010

karuna
Oct 3, 2006
I need to sort a collection: LinkedList<ArrayList<String>>

I need to sort it based on an element in the ArrayList, the last element.

I am looking to write my owm comparator and use Collections.sort but I'm having trouble getting some examples for a comparator that I can adopt.

Anyone care to have a look at how I would go about writing the comparator? Would be much appriciated!

Note: the last element in ArrayList<String> can be cast to a Double

Thanks

hlfrk414
Dec 31, 2008
code:
LinkedList<ArrayList<String>> ll = ...;
Collections.sort(ll, new Comparator<ArrayList<String>>(){
    public int compare(ArrayList<String> arg0, ArrayList<String> arg1){
        return new Double(arg0.get(arg0.size()-1)).compareTo(new Double(arg1.get(arg1.size()-1)));
    }
});

hlfrk414 fucked around with this message at 18:28 on Mar 5, 2010

karuna
Oct 3, 2006

hlfrk414 posted:

code:
LinkedList<ArrayList<String>> ll = ...;
Collections.sort(ll, new Comparator<ArrayList<String>>(){
    public int compare(ArrayList<String> arg0, ArrayList<String> arg1){
        return new Double(arg0.get(arg0.size()-1)).compareTo(new Double(arg1.get(arg1.size()-1)));
    }
});

EDIT: nevermind, works now. I was changing the list before printing it so thought it wasn't sorting correctly.

Thanks man much appriciated.

karuna fucked around with this message at 18:40 on Mar 5, 2010

Kaltag
Jul 29, 2003

WHAT HOMIE? I know dis ain't be all of it. How much of dat sweet crude you be holdin' out on me?
*resolved

Kaltag fucked around with this message at 14:25 on Mar 8, 2010

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


Speaking of that pesky iterator . . . I used your guys' advice and tried to write it. I suspect that it's not working correctly though. Could you guys take a look at it and see if it makes sense? I've looked it over several times and I just can't see it.

code:

import java.util.Iterator;


import cs367.p2.*; //Some thing the instructor made for this project

/**
 * Implementation of the {@link Iterator} interface for use with
 * {@link SimpleLinkedList} and {@link DoubleListnode}. <strong>Modify this
 * class to implement a constructor, the required {@link Iterator} methods, and
 * any private fields or methods you feel are necessary.</strong>
 * 
 * @param <E>
 *            the type of data stored in the list
 */
public class SimpleLinkedListIterator<E> implements Iterator<E> {

    // TODO add any private fields or methods that you need
	DoubleListnode<E> curr;
	SimpleLinkedList<E> thisList;

    // TODO document and implement a constructor, which only
    // SimpleLinkedList.iterator() should call
	public SimpleLinkedListIterator(SimpleLinkedList<E> list) {
		curr = list.head;
		thisList = list;
	}

    @Override
    public boolean hasNext() {
    	boolean retval = true;
    	if (curr.getNext() == null || curr.getNext().getData() == null) {
    		retval = false;
    	}
        return retval;
    }

    @Override
    public E next() {
        DoubleListnode<E> temp = new DoubleListnode<E>(curr.getPrev(), curr.getData(), curr.getNext());
        if (this.hasNext()){
            curr = temp.getNext();
        }
        return temp.getData();
    }

    @Override
    public void remove() {
        thisList.remove(curr);
    }
}

Max Facetime
Apr 18, 2009

Your hasNext() has two ways to check if there are more nodes after the current. You should choose one way and stick with that. How is hasNext() going to work on an empty list?

Adbot
ADBOT LOVES YOU

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


I am in posted:

Your hasNext() has two ways to check if there are more nodes after the current. You should choose one way and stick with that. How is hasNext() going to work on an empty list?

Is this good?

code:
public boolean hasNext() {
    	boolean retval = true;
    	if (curr.getNext() == null || curr.getData() == null) {
    		retval = false;
    	}
        return retval;
    }
If the problem isn't there then it might be in my list class. Could you please look over it and tell me if you see anything? It's a little long for a post so I pastebin'd it if that's OK: http://pastebin.com/q6iHEP5V Again, I'm just too inexperienced to see why it isn't working. I've only really tested the one-argument add, size, and get and I know that at least one of them isn't working.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply