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
Incoherence
May 22, 2004

POYO AND TEAR

icehewk posted:

After six weeks of my first programming course, I know absolutely nothing. The instructor doesn't teach along with the book, nor does he teach much of the ideas behind the code. To borrow a lovely analogy, it's like he goes over what you can nail where without explaining where the spot to be nailed is located or why it's being nailed. As such, I've taken it upon myself through the resources provided here to learn Java outside of class and hope I can catch up before the next project is assigned. Unfortunately, my latest project is due Wednesday and I don't know where to begin. Can you guys help?
From the skeleton given, basically all you need is to implement plus(), minus(), times() and dividedBy(). That greatly simplifies your problem.

Let's walk through plus(): First, how do you add fractions? If you have two fractions a/b and c/d, what is their sum in terms of a, b, c, and d? Second, which field of which object corresponds to a, b, c, and d?

Adbot
ADBOT LOVES YOU

Incoherence
May 22, 2004

POYO AND TEAR

icehewk posted:

It would be a+c when b=d. How would you go about finding the LCD? Is the data field the part that corresponds to a, b, c and d?
No, if b = d, then it'd be (a+c)/b. I'm being pedantic here for a reason: this isn't a Java problem, but an algorithmic problem, and if you can't specify how to add fractions algebraically how do you expect to tell the computer how to?

And, as previously mentioned, don't worry about the LCD. Look at the example output for a hint as to what denominator the result should have.

NotHet posted:

Given the following conditions:
code:
		double anArray[] = {9.2, 9.3, 9.0, 9.9, 9.5, 9.5, 9.6, 9.8};
		double lowest = 10, highest = 0, sum = 0, fin;
		for(int i = 0; i < anArray.length; i++) {
			if(anArray[i] < lowest) { lowest = anArray[i]; }
			if(anArray[i] > highest) { highest = anArray[i]; }
			sum = sum + anArray[i];
		}
		fin = (sum - highest - lowest);
		System.out.println( fin );
fin is equal to 56.90, but the application prints 56.89999999999999; Is this due to a quirk in Java's System.out class? What should I do in a case such as this when I want to print a double?
It's a floating point quirk. If you HAVE to have 56.9 for some reason, round it.

Incoherence fucked around with this message at 20:39 on Feb 26, 2008

Incoherence
May 22, 2004

POYO AND TEAR

icehewk posted:

So what would I write to find the common denominator? I really don't understand much of the actual language beyond syntax and reference.
We're not even talking about the language here. How would you do it if you were just writing an algebraic formula?

Incoherence
May 22, 2004

POYO AND TEAR

icehewk posted:

Seems the uni knows how tough the class is so they provide a free tutor three times a week. Algebraically, a/b and c/d would require b*d and d*b along with a*d and c*b. That would be (a*d)+(c*b) over (b*d), right?
Yeah, that. Check that against their example; you should get exactly the same thing they do.

Okay, now that's step 1. Step 2 is to figure out how to express each of a, b, c, and d in terms of the two objects.
code:
  public RationalNumber plus(RationalNumber r){
    //  just think of the rules for adding fractions
  }
Your choices are numerator, denominator, r.numerator, and r.denominator. Then just substitute those four names into the algebraic formula you already have, and test it.

Incoherence
May 22, 2004

POYO AND TEAR

Emo.fm posted:

I'm writing a program (yes, homework for intro CS) that plays a quick card game between two computer players and then returns who won (player 1 or 2, it's a random game of luck so theoretically I should be able to run it 1000000 times and see 50/50 winning percentages). I believe my code is correct, and I can run it as many times as I want with no exceptions if I actually run it repeatedly by hand -- but if I insert a for loop to get it to run multiple trials, I invariably end up with an array index out of bounds exception. I'm really confused by this because all of the variables (arrays of cards, stuff like that) are declared either in the for loop or the method called from within the for loop. What kinds of things should I be looking for? What could cause the program to screw up when run multiple times within itself, when I can run it so many times from outside with no incidents, so to speak?
Unless you're catching the exception and eating it, the exception message should specify exactly what the offending index is, and possibly what line it occurred on.

Off the top of my head, make sure you realize that Java (and C and its derivatives) arrays are 0-based, and an array of N elements has valid indices from 0 to N-1 inclusive (and index N will cause an exception).

It has nothing to do with your for loop, which I assume is just counting runs and isn't actually doing anything in the body of the loop, except that running it 1 million times makes it more likely that a bug based on random input (and presumably there's random input somewhere in your program) will manifest itself.

It may be worth posting your code, or at least posting the exception message.

Incoherence
May 22, 2004

POYO AND TEAR

MEAT TREAT posted:

I agree with posting your code. Your problem doesn't make much sense, it should work.
I have no doubt that there's an error in it, but I'm guessing that it has nothing to do with the loop. Start by looking at the actual exception message, and be glad you're not writing C and just looking at the words "Segmentation Fault".

Incoherence
May 22, 2004

POYO AND TEAR

itsasnake posted:

Yeah, i sorted the list into an ArrayList of 1050 elements. Can you elaborate please?
If the list is sorted, then presumably all of the duplicates are together and you're only counting "runs" of a given element as opposed to total occurrences (in other words, you can get rid of the HashMap in his code). Slightly less space taken, slightly worse time bounds (although for 1050 elements it doesn't really matter).

Something like this:
code:
Object current = list.at(0);
int currentCount = 1;
Object max = null;
int maxCount = 0;
for (int i = 1; i < list.size(); i++) {
  Object temp = list.at(i);
  if (temp.equals(current)) {
    currentCount++;
  } else {
    if (currentCount > maxCount) {
      max = current;
      maxCount = currentCount;
    }
    currentCount = 1;
    current = temp;
  }
}
if (currentCount > maxCount) {
  return current;
} else {
  return max;
}

Incoherence
May 22, 2004

POYO AND TEAR

Sterra posted:

How does one go about implementing the externalizable interface so that a treelike object can't overflow the stack?

I came across this issue and while realistically it shouldn't affect me I couldn't figure it out.
If you're really making trees too big for the stack, don't make them recursive, or make them less recursive.

Incoherence
May 22, 2004

POYO AND TEAR

Ranma4703 posted:

I just started a co-op (my first job programming), and one thing I see in a lot of the code is the following:
private final int ONE = 1;
private final double FIVE = 5.0;


I always thought that was bad coding; why not just use 5.0 in the code. The only thing I can think of is if you want to be able to modify all references of "FIVE" in one location. However, it probably shouldn't be named "FIVE" if you want to do that, because if you change it to FIVE = 6.0, then the name of the variable isn't really useful anymore.

Is this bad coding practice, or am I just stupid?
This is an overblown case of "don't have magic numbers in code".
code:
private final int NUM_FOOS_IN_BAR = 5;
is fine because you might want to change the number of foos in a bar. You will never want to change the definition of 5, I hope, and if FIVE refers to something in particular it should be named for what it does rather than FIVE.

The better answer is csammis's: ask them about it. If there's some good reason for it you might want to know what it is.

quote:

They also do multiple return statements in methods often, which I thought was another no-no.
There's nothing intrinsically wrong with that, unless the method has some sort of cleanup associated with it that you don't want to do multiple times. On the scale of "control flow constructs that make code unreadable", multiple return statements are fairly low.

Incoherence
May 22, 2004

POYO AND TEAR

Drumstick posted:

yay, thanks for that catch.

I have one more problem im running into. How can i check the values next to each in an array?

say, if this would be how it is saved in the array


I need to be able to check the value for each adjacent item in the array. Is this possible, and any hint on how to do it?
Suppose the point in question is lifegame[x][y]. What are the indices of the four adjacent points (or eight, if you want to go that way)?

Your question makes me unsure whether you understand what's going on here, so I'm being intentionally general to make sure we're not doing your homework for you or something. If you're having trouble, draw a picture of one of your grids and label each row and column with an index, then try and generalize to the question I asked above.

There's one catch: you'll want to check that each of your four/eight adjacent points are inside the matrix, but what you want to do about that will depend on whether you want to wrap around on edges or just drop them.

Incoherence
May 22, 2004

POYO AND TEAR

MEAT TREAT posted:

I've always wondered what people do when you just want to drop them. In the past I've surrounded that block of code with a try/catch that doesn't do anything when an IndexOutOfBoundsException is thrown.
code:
if (x >= 0 && x < max_rows && y >= 0 && y < max_cols) {
  // this point is obviously inside the matrix!
}
If I ever saw anyone use a try/catch I'd go put it in the Coding Horror thread posthaste.

Drumstick posted:

if i understand what your asking, you want the positions of the 8 adjacent 'boxes'


Im assuming this is what you meant by that.
Yes, and that should get you very close to answering your question on how to check the 8 adjacent boxes. Isn't the Socratic method wonderful?

quote:

As for checking, they will need to drop off and not wrap around. Let me know if i understood what you were asking.
Okay, then you want to guard against checking out-of-bounds boxes in much the way I posted above.

Incoherence
May 22, 2004

POYO AND TEAR

clayburn posted:

Haha it might be homework. I really just needed a point in the right direction like you gave, just some methods to look at. I've considered putting the words in some sort of array, I'm just worried about the efficiency of putting them there in the first place. I'll definitely check those methods out though, thanks.
“The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson

Incoherence
May 22, 2004

POYO AND TEAR

clayburn posted:

I have a question about the HashMap class. I have populated a HashMap with a simple object I have created, basically consisting of two strings. One of these strings holds a segment of text from a file, the other holds the file name. What I want to do is to use the HashMap.contains method to determine if a particular string matches any of the text segments, and then use whatever get method is in the class to determine the file name. I figured that overriding the hashcode method would do the trick; I defined the hashcode method of the class to return the hashcode value of the string that we will be searching for. Apparently, this doesn't quite do the job. I am fairly new to hash tables, so if anyone could give me a few tips it would be very appreciated.
1. First rule of hashCode(): if two objects have the same hashCode(), equals() should return true on them as well. The converse is usually the part people trip over (overriding equals() but not hashCode()). I'm not sure you keep that invariant, which you should do.

2. You're not being exactly clear on what you're doing. What it sounds like is that you're building an index and searching it, so your hash map looks like this:
"foo" -> "file1.txt"
"bar" -> "file2.txt"
"baz" -> "file3.txt"
"cat" -> "file1.txt"
and your search term is "foo". In this case, the strings should be the keys, and the filenames should be the values, and contains() will do what you want. But it sounds like either (a) the strings aren't the keys (what is, then?), (b) you're actually using HashSet instead of HashMap (you want HashMap), or (c) this is not what you mean at all, at which point you should clarify.

Incoherence
May 22, 2004

POYO AND TEAR

poopiehead posted:

Unless I'm reading this wrong, you got it backwards.

This is a valid, but stupid implementation of a hashcode.
code:
int hashcode()
{
  return 0;
}
if a.equals(b) the a.hashcode() should == b.hashcode()

logically equivalent but put in a different way:

if a.hashcode() != b.hashcode() then a.equals(b) should be false.
I didn't get it backwards (both directions are equally true), but I should have been more clear about that being an if-and-only-if statement:

If you override either hashCode() or equals(), you should override both such that
a.hashCode() == b.hashCode() iff a.equals(b) (and b.equals(a))

Incoherence
May 22, 2004

POYO AND TEAR

poopiehead posted:

Sorry. That't not correct though. Multiple values can have the same hash code. You want to minimize collisions, but they will happen.
Yeah, you're right. I'll go back to my fantasy land of collision-less hashes now...

quote:

These are both valid hash functions but wouldn't be if a.hashcode()==b.hashcode() -> a.equals(b)

return 0; \\1.hashcode() == 2.hashcode but 1 != 2
return x % 35; \\ 1.hashcode() == 36.hashcode() but 36 != 1
"Valid", but you could do better in either case.

Incoherence
May 22, 2004

POYO AND TEAR

CrusaderSean posted:

So in terms of programming practice, which of the following is better?

void someMethod(Object obj...) { ... passed in object value may change ... }
or
Object someMethod(Object obj...) { ... explicitly return changed object ... }

I see people using the first one because they want to change multiple objects in a method and can't return multiple objects. But in reality it is not really "void" in the sense that inputs can change in value so it might be misleading. Maybe this is a non-issue and everyone knows how reference works in Java... I was just really confused the first time I saw someone do that.
void simply means there's no return type; it doesn't mean that nothing will be modified. In general, Java's "we're hiding pointers from you but they're still there!" semantic is something you trip over once then learn.

Incoherence
May 22, 2004

POYO AND TEAR

Emo.fm posted:

Sorry, I'm still a little confused. Let's say I have two files, MyApplet.java and SmallClass.java. If I want to load an image in SmallClass.java, how do I do it? Moving all of the image related operations that occur in SmallClass to MyApplet is not an option for me right now. There must be some way to load an image in a class that isn't an applet, right?
One possibility is to give SmallClass a reference to MyApplet, assuming that you're making SmallClass from MyApplet.

Incoherence
May 22, 2004

POYO AND TEAR

Phillyt posted:

If we can't assume tab characters, how exactly can I parse this file? I don't want code written but I am curious what someone would do.
If you are guaranteed nothing at all about the format, then you can't possibly parse it, because someone could have the name "123 45" and then you're pretty well hosed. Obviously you are guaranteed SOMETHING about the format, even if it's not what you would like, unless this is a trick question in which case you should have already asked the teacher for clarification. For example, "each field is separated by some sort of whitespace, not necessarily a tab" is sufficient. To make your problem somewhat easier, as I understand it you don't actually care about the format of the student ID or the login ID, only that you can distinguish the student ID from the name and the login ID from the email.

Basically, you want to tokenize "words" such that each word belongs to exactly one field, even if each field is not contained in a single word. So, in your example:
code:
Doe,
John
H.
123-45-6789
doe6789
jdoe@foo.net

Incoherence
May 22, 2004

POYO AND TEAR

Phillyt posted:

How would you distinguish between the three words at the top to make it the name? I am probably going to just write the program assuming /t as the token and just get partial credit. Seems a lot easier.
Already covered to some extent, but what I was trying to get you to say is the following:
1. None of the fields except for the name can have spaces in them.
2. Fields are separated by something, just not necessarily a tab (it could very well be a space), and that "something" obviously doesn't belong to any of the other fields. Ideally, fields are separated by some sort of white space.

Given that, if there are N words in the line, the Nth word is the email address, the N-1th is the login ID, the N-2nd is the student ID, and the first N-3 words are the name.

Another acceptable answer would be that the student ID is in a specified format (which you could look for, and everything before it is obviously the name), and the email address is in a specified format which you could pull out.

Incoherence fucked around with this message at 09:07 on May 23, 2008

Incoherence
May 22, 2004

POYO AND TEAR

adante posted:

hi, I want to readLine() from multiple BufferedReaders and do the same thing with the result (after some transforms, depending on the specific BufferedReader instance.

Is there a better way of doing it than instantiating a thread for each reader?
Depends how many readers you have relative to how long it takes for each one. If you have, say, a whole lot of readers, but for each one all you want to do is read a line, munge it a bit, and move on, the cost of starting that many threads may become a nontrivial portion of your runtime, at which point thread pools (java.util.concurrent.something) become an option.

This article is old, but explains what I just said in more detail: http://www.ibm.com/developerworks/library/j-jtp0730.html

Incoherence
May 22, 2004

POYO AND TEAR

adante posted:

Right, I'm familiar with thread pools to an extent but my question was more: how do I do it when readLine() is a blocking operation and there is (as far as I can see) no non-blocking alternative?
The example you give calls readLine() within a thread, so thread pools don't really change that problem. I didn't get the impression from your post that that was your big problem, but maybe I wasn't reading it closely enough. If the readers are all reading from the same place (disk, network), they're probably going to be queued by something anyway. (I'm pretty sure hard disks can't read 500 different files at once. Could be wrong, of course.) You may as well have threads processing while they're waiting for I/O, and you may as well use a thread pool since you really don't need to start up and tear down N threads just to keep busy while you wait for N readLine calls.

Basically, the only change I suggested is that instead of starting each "read, DoThing" task in its own thread, as your example does, you'd start each in a thread pool, which would have approximately the same result but wouldn't need to set up quite so many threads.

Incoherence
May 22, 2004

POYO AND TEAR

adante posted:

right, and what I meant is, I don't know how to do this. I don't see how it is possible to have N threads servicing M BufferedReaders where N < M. Maybe there is a misunderstanding here, but I think code speaks for itself. If you could provide some code/pseudocode that illustrates how to do this I'd be really interested.
That's kind of the idea behind a thread pool. Instead of creating M threads that do one task apiece (as your example does), you create a thread pool with N threads, and you add your M tasks to the thread pool. The thread pool is usually implemented as a producer/consumer setup: the thread pool controller has a queue of work to do, and as worker threads finish what they were doing before they get work from the queue.

In particular, what I think you want is this. This code sample is pretty close to what you're doing, I guess.

Incoherence
May 22, 2004

POYO AND TEAR

adante posted:

Ok, MY point is that you guys keep suggesting I use a threadpool. Yes, a N-thread threadpool means my M threads will be very simple and the servicing goes into the N threads, but now I have M + N threads. This is not less than M threads. This is more than M threads! To re-iterate, my original question was if I could do it with less than M threads (well literally, 'Is there a better way of doing it than instantiating a thread for each reader?').
Let's back up a second. You could, if you want, instantiate M readers in one thread. If you're looking at a threaded solution at all, this is obviously a step back, but I just want to make it clear that it's possible. So I'm not clear on why you think you would need M + N threads in any version of a thread pool. You need M readers (which have nothing to do with threads), and N threads.

Here's an example (borrowing heavily from triplekungfu, and probably not working):
code:
public class Dongs {
  public void doTheThingWithTheStuff(int numThreads) {
    List<BufferedReader> readers = makeSomeReadersSomehow();
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    // there needs to be a final in here somewhere because we're passing this to
    // an anonymous inner class, but I don't want to have to make an example that
    // compiles so you'll have to figure out exactly where it goes
    for (final BufferedReader reader : readers) {
      threadPool.execute(new Runnable() {
        public void run() {
          String s = br.readLine()
          // stuff here
          DoThing(s);
        }
      });
    }
    threadPool.shutdown();
  }
}
So, you have M readers (however many are created by makeSomeReadersSomehow()), and N threads (numThreads). Not M+N threads. I'm not sure where M+N came from.

Incoherence
May 22, 2004

POYO AND TEAR

pogothemonkey0 posted:

That is exactly what I thought too, but it doesnt work well. After taking the time to implement, I realized that it wont work. Because you can only have one instance of a "key," I cant have different values associated with one string.

I need to be able to store Cat-dog as well as Cat-rat. Because there can be only one cat key, the old one is erased. I need to find a better way.
Unless I'm misunderstanding your problem, what you want is to make some sort of pair structure (not concatenating, unless you can concatenate them with some special character between them that's not going to be in your input). Make a Pair object with your two strings (I don't think there's a builtin class for this but it shouldn't be hard to write), declare a HashMap<Pair, Integer>, add to it with put(new Pair(firstString, secondString), value), and then everything's happy. Only problem with this is that you end up making a lot of temporary Pair objects.

Incoherence
May 22, 2004

POYO AND TEAR

dvinnen posted:

The keyword 'this' tells java you mean to change the object's global variable. If you use the same variable name in a method Java assumes the the method variable is not the same as the global. For example from some code I am looking at:
Well, except that there's no name ambiguity in that code. In decreaseSalaryByPercent, salary always refers to a class variable, not a parameter. You only NEED this.something if you have a class variable named something AND a method parameter named something. Another way around this is just to name your class variables and parameters differently.

This might explain why changing salary to this.salary doesn't do anything in Sarah Sherman's example, but why it would do something in the BinaryFileMessage example.

Incoherence
May 22, 2004

POYO AND TEAR
Hm, somehow missed this earlier.

Sarah Sherman posted:

Also, did you guys ever have a teacher who forced you to code in a certain style? My Java teacher is forcing us to use Allman indenting (which I use anyway so it doesn't really matter), and having us put those large comments before each method or class. I was surprised that he is making us do this; I thought that an important aspect of programming was being able to code in your own style.
Ow, my brain hurts. If you're working on a project of even moderate size, an important aspect of working together is being able to use a coherent style (so you can read each other's code), and commenting your code (so you can understand each other's code, or you can understand your own code 3 months from now). While students hate this because it seems silly to write 5 lines of comments for a 3 line function, it's For Your Own Good (tm) and someday you'll be glad you commented this cute trick you pulled in one method way off in a corner of the project.

Adbot
ADBOT LOVES YOU

Incoherence
May 22, 2004

POYO AND TEAR
I suspect that part of your problem is that you're checking q1.size() and q2.size() every time through the loop, even though you're also decreasing the size of the queue, so you only get halfway through before the loop ends.

Also, you only put four pop() statements at the end, not five.

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