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
trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

pearofducks posted:

Quick concurrency question (I'm new to threads). I've got a homemade generic linked list, most of the operations on it take place inside a loop, and only one operation actually uses the list. So I'm wondering if its possible to have the linked list operation run in its own thread, and the loop to keep going. I've read up on it some and it seems like it just provides the ability to override the run method, but I'd like to have any of the linked list actions be in their own thread. Is this possible? If so can someone just give me a brief idea of what to do?

Why'd you roll your own linked list when the JDK provides you with one (java.util.LinkedList) that has built-in concurrency support (using the Collections class) already?

That said, you probably could do what you want to do but you're being pretty vague about what "operations" and "actions" you need to perform. Can you be a little more precise?

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

pearofducks posted:

Quick concurrency question (I'm new to threads). I've got a homemade generic linked list, most of the operations on it take place inside a loop, and only one operation actually uses the list. So I'm wondering if its possible to have the linked list operation run in its own thread, and the loop to keep going. I've read up on it some and it seems like it just provides the ability to override the run method, but I'd like to have any of the linked list actions be in their own thread. Is this possible? If so can someone just give me a brief idea of what to do?

It's certainly possible, and if you really just want to know how to allocate a thread to perform a task which only accesses immutable data and doesn't need to communicate with the rest of the program, I'd be happy to tell you. However, that doesn't sound like the sort of thing you have in mind, and so I feel obliged to warn you that concurrency is an extremely complex and difficult programming area with many, many pitfalls to it, and it is not really feasible to explain it in the scope of a forum thread. Suffice it to say that just naively allocating threads for incidental tasks will almost certainly not make your program faster.

LakeMalcom
Jul 3, 2000

It's raining on prom night.
This is true. Honestly, if the idea is to naively create threads for the above reasons, then you're probably using the wrong data structure. Work on your algorithm and work with your data, then once you've gotten there, work on concurrency and optimization.

pearofducks
Jan 21, 2003

quack?
Sorry for the lack of clarity before. I was using this as more of a learning exercise, hence why I rolled my own linked list and the desire to make it concurrent. What I'm confused by is how I'd make both remove and add (which both need to traverse the list to remove at an index) threaded. Like I said before, with my current limited knowledge it seems like you can only implement run, so I don't know how to bridge the gap. There are two areas of this project I wanted to see implement this setup.

Initial list population: Could be importing unsorted data, but then populating the list sorted, so it will be using add(index, element), and should have plenty of time before the list is actually used.

Element removal: Whenever an element is removed (again at an index), a loop continues to run, but doesn't need the list again for enough time that the element should be able to be removed.

\\vvvvv awesome, thanks for the help guys

pearofducks fucked around with this message at 00:33 on Sep 29, 2008

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
Okay.

First off, the thread has nothing to do with your data structure. There's no way you can just say "aha, all the operations on this data structure will magically happen in a different thread"; you'll have to change the implementation of each operation to create a thread to do the work. So the add method will look something like:

code:
// These variables are marked 'final' so that I can close on
// them in the anonymous inner class;  otherwise, I'd need
// an explicit class with these variables as explicit instance
// fields (which is exactly what this will compile to).
public void add(final int index, final T value) {
  new Thread(new Runnable() {
    public void run() {
      // do the removal work
    }
  }).start();
}
You'll need to use locks to protect your list data. Good luck.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Without putting to fine a point on it, you will have tremendous problems if you think that you'll have "enough time" to modify a list before some other thread can access it.

To answer your question, check out the synchronized keyword and the Collections.synchronizedList() method, if you implement List then that will basically solve it for you. Also, there are a few books on Java concurrency that are pretty good: specifically Java Concurrency in Practice and Concurrent Programming in Java: Design Principles and Patterns if you are interested.

Concurrency is frighteningly difficult to do correctly, especially with some of Java's more quirky semantics and rules involving synchronization.

Boz0r
Sep 7, 2006
The Rocketship in action.
I've been learning to write code in BlueJ, but it's poo poo. What IDE should I get instead?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Boz0r posted:

I've been learning to write code in BlueJ, but it's poo poo. What IDE should I get instead?

Didn't know that was still out, used that back when I took my first programming class in college (used C++ during HS, Clemson taught Java).

Eclipse and Netbeans are the two best free ones. Lot of people like IntelliJ IDEA, never used it but you have to pay for it. Fore the most part I develop with Eclipse but have been playing around with Netbeans 6.5 Beta because of the improved webservices and groovy support.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
Hey guys. I'm having a slight problem with this simple java program i'm writing for my class. Here is my code:

http://pastebin.com/m71a64ee4

I'm pretty sure I got everything working, except for some reason my methods increaseSalaryByPercent() and decreaseSalaryByPercent() methods arn't really doing anything; they're just returning the same salary that was it's argument. This is my first program in java, so please don't bash me too hard if it turns out it's an easy answer.

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.

sonic bed head
Dec 18, 2003

this is naturual, baby!

Sarah Sherman posted:

Hey guys. I'm having a slight problem with this simple java program i'm writing for my class. Here is my code:

http://pastebin.com/m71a64ee4

I'm pretty sure I got everything working, except for some reason my methods increaseSalaryByPercent() and decreaseSalaryByPercent() methods arn't really doing anything; they're just returning the same salary that was it's argument. This is my first program in java, so please don't bash me too hard if it turns out it's an easy answer.

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.

You need to use this.name and this.salary to change those variables in your increase/decrease methods.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

sonic bed head posted:

You need to use this.name and this.salary to change those variables in your increase/decrease methods.

Thought that at first, but it actually is a problem with integer math. He is passing a into into the increase/decrease functions then dividing by 100.

Sarah Sherman: in the declartion, change it from "int percent" to "double percent" to fix it. In any language that supports types you get to have fun with integer math. You think (Percent/100) will return .1 or whatever because you are taking decimal points for granted. Because Percent is declared as an integer Java will treat the product of the division function as a integer as well and that means chomping off the decimal point. So .5 becomes 0, 1.9 becomes 1, ect. Either make percent floating point or cast it to double by placing (double) in front of it.

code:
 public double decreaseSalaryByPercent(double percent){
                salary = salary - ((percent/100) * salary);
                return salary;
 }

or

public double decreaseSalaryByPercent(int percent){
                salary = salary - ((double)(percent/100) * salary);
                return salary;
 }
There other issues with your code but I doubt you have gotten to the idea of 'private' variables and such.

lmao zebong
Nov 25, 2006

NBA All-Injury First Team
^^Ah, this seemed to have fixed it. Thanks!

sonic bed head posted:

You need to use this.name and this.salary to change those variables in your increase/decrease methods.
I'm sorry, but I don't understand exactly what you mean :(

should I change the code to look like this?:
code:
  public double decreaseSalaryByPercent(int percent)
  {
	  this.salary = salary - ((percent/100) * salary);
	  
	    return this.salary;
  }
When i tried this, I was still having the same problem. Sorry for not understanding, I'm just learning java and OOP and still having some difficulties with some of its concepts.

lmao zebong fucked around with this message at 20:04 on Sep 29, 2008

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Sarah Sherman posted:

^^Ah, this seemed to have fixed it. Thanks!

I'm sorry, but I don't understand exactly what you mean :(

should I change the code to look like this?:

When i tried this, I was still having the same problem. Sorry for not understanding, I'm just learning java and OOP and still having some difficulties with some of its concepts.



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:

code:
public class BinaryFileMessage {
	private String binaryBase64Object;

        public void setBinaryBase64Object(String binaryBase64Object) {
		this.binaryBase64Object = binaryBase64Object;
	}
}
The line __this.binaryBase64Object = binaryBase64Object;__ tells Java to set the methods instance of 'binaryBase64Object' to the global instance.

For more detail:

http://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html

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.

the onion wizard
Apr 14, 2004

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.

Yep, in one of my earlier classes we could lose up to 20% per assignment for incorrect formatting, and every class except the earliest couple would dock marks for missing or poor javadoc.

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

triplekungfu posted:

Yep, in one of my earlier classes we could lose up to 20% per assignment for incorrect formatting, and every class except the earliest couple would dock marks for missing or poor javadoc.

I had a drat S/390 Assembler professor knock of 67% of an assignment because of lack of comments. That might sound acceptable until I mention that the uncommented lines were printlines. Goddamn that guy.

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.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Incoherence posted:

Hm, somehow missed this earlier.
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.

My only counter argument to this, how often do you go back and look at your own code from semesters past?

Boz0r
Sep 7, 2006
The Rocketship in action.
Does anyone know if there is some sort of cool algorithm for cutting up a random convex/concave polygon into triangles in a smart way, or if it's impossible to do automatically?

the onion wizard
Apr 14, 2004

MEAT TREAT posted:

My only counter argument to this, how often do you go back and look at your own code from semesters past?

These things don't really pay off while you're still at uni. But they're very important skills once in the workforce.

defmacro
Sep 27, 2005
cacio e ping pong

Boz0r posted:

Does anyone know if there is some sort of cool algorithm for cutting up a random convex/concave polygon into triangles in a smart way, or if it's impossible to do automatically?

You're thinking of polygon triangulation, Siedel's Algorithm handles this.

Startacus
May 25, 2007
I am Startacus.
I have a quick question can anyone look at my code and tell me why it's printing 1, 5, 3, 2 when it should be printing 5 4 3 2 1. I'm trying to emulate a stack using two queues.

Thanks.

code:
public class MyQueueStack {

    Queue<Double> q1 = new LinkedList<Double>(); 
    Queue<Double> q2 = new LinkedList<Double>();
    
    
    public void push(Double data)
    {
        if(q1.peek() == null)
        {
            q1.add(data); 
        }
        
        else
        {
            for(int i = 0; i < q1.size(); i++)
            {
                q2.add(q1.remove());
            }
            
            q1.add(data); 
            
            for(int i = 0; i < q2.size(); i++)
            {
                q1.add(q2.remove()); 
            }
        }
    }
    
    public double pop()
    {
        if(q1.peek() == null)
        {
            double temp = 0;
            System.out.println("The stack is empty");
            return temp; 
        }
        
        else
        {
            double pop = q1.remove();
            return pop;
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        MyQueueStack queueStack = new MyQueueStack(); 
        
        queueStack.push(1.0);
        queueStack.push(2.0);
        queueStack.push(3.0);
        queueStack.push(4.0);
        queueStack.push(5.0); 
        
        System.out.println(queueStack.pop());
        System.out.println(queueStack.pop());
        System.out.println(queueStack.pop());
        System.out.println(queueStack.pop());
        
    }

}

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.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Edit: Dumb poo poo, should pay attention what I'm doing. You were doing it right.


Also what Incoherence said, that is why you are only getting 4 elements back I think.

lamentable dustman fucked around with this message at 19:55 on Oct 1, 2008

Startacus
May 25, 2007
I am Startacus.

Incoherence posted:

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.

That was it. I changed the q1.size() to while(q1.peek() != null).

Thanks for the help.

icehewk
Jul 7, 2003

Congratulations on not getting fit in 2011!
Edit: got it.

icehewk fucked around with this message at 00:07 on Oct 5, 2008

craig8429
Aug 26, 2007
Goons I ask for your help with a simple program, not exactly sure what im doing wrong this is the practice for my homework for java class I keep getting errors no matter what I do.

//This is a program to tell simple intrtest
//Written by
//october 5th, 2008
//JDK 1.6

import javax.swing.*;
import java.text.*;
public class Chp4prac1
{
public static void main (String [ ] args)
{
String response;
response = JOptionPane.showInputDialog(null, "Dollars you would like to borrow");
double Dollars = Double.parseDouble(response);
{
String response;
response = JOptionPane.showInputDialog(null, "Interest is");
double Interest = Double.parseDouble(response);
String response;
{
response = JOptionPane.showInputDialog(null, "years");
double years = Double.parseDouble(response);
Interest over time=Dollars*Interest*years;
{
}// ends main method
}// ends program

At first I thought it was suppose to be Int for the year and interest but I'm having no luck at all. the end always pops an error usually line 24 or 25 saying missing } even though its there. For a simple interest program I'm so confused. if against the rules to post practice work i apologize in advance. i'm just utterly confused.

zootm
Aug 8, 2006

We used to be better friends.
The third-last line has a { where there should be a }, for starters. Also you seem to have pasted the same bit of code over itself a few times?

craig8429
Aug 26, 2007

zootm posted:

The third-last line has a { where there should be a }, for starters. Also you seem to have pasted the same bit of code over itself a few times?

I was under the impression that copying the same style of a line would also pop the Joptionpane up for the interest rate and years to be entered?

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

craig8429 posted:

snip
Put your code in [code ][ /code] blocks, and use proper indentation, like thus:
code:
//This is a program to tell simple intrtest
//Written by 
//october 5th, 2008
//JDK 1.6

import javax.swing.*;
import java.text.*;
public class Chp4prac1
{
    public static void main (String [ ] args)
    {
        String response;
        response = JOptionPane.showInputDialog(null, "Dollars you would like to borrow");
        double Dollars = Double.parseDouble(response);
        {
            String response;
            response = JOptionPane.showInputDialog(null, "Interest is");
            double Interest = Double.parseDouble(response);
            String response;
            {
                response = JOptionPane.showInputDialog(null, "years");
                double years = Double.parseDouble(response);
                Interest over time=Dollars*Interest*years; 
                {
                }// ends main method
            }// ends program
Notice a problem?

craig8429
Aug 26, 2007

Jethro posted:

Put your code in [code ][ /code] blocks, and use proper indentation, like thus:

That actually does help a fair bit. I just noticed that I completely messed up the panes.I fixed it all however it has lead to another issue, when I do the formula Dollars*years*rate/100 it refuses to show it in the pane like i need it. I'm a play with it a bit more and see if i can get it. Thank you so far by the way everyone I appreciate the tips. Trying to learn to program from a book isn't as easy as i had hoped.

Edit here is the redone version.

code:
 
//This is a java program
//Craig 
//Date
//JDK 1.6
import javax.swing.*;
import java.text.*;
public class Chp4Proj12
{
	public static void main (String [ ] args)
	{
		String response;
		response = JOptionPane.showInputDialog(null, "Dollars Borrowed");
		double Dollar;
 		double rate;	
 			String response2 = JOptionPane.showInputDialog(null, "interest rate?");
  			rate = Double.parseDouble( response2);
			double years;
 				String response3 = JOptionPane.showInputDialog(null, "years");
  				years = Double.parseDouble( response3);
				System.exit(0);
				
	}// ends main method
}//ends program 

craig8429 fucked around with this message at 02:47 on Oct 6, 2008

magnetic
Jun 21, 2005

kiteless, master, teach me.
code:
public class Chp4prac1
{
    public static void main (String [ ] args)
    {
    	//Response is a lovely name for a variable, also you can only 
    	//declare the variable one time in a given scope.
        String sDollars =
            (String) JOptionPane.showInputDialog(null, "Dollars you would like to borrow");

        //because there are two types (String and double) 
        //I will preface the variable with a letter to signify the type.
        double dDollars = 
             Double.parseDouble(sDollars);
        
        //Because I don't know what is coming back from the 
        //OptinPane I will cast it  with (String)
        String sInterest = 
            (String) JOptionPane.showInputDialog(null, "Interest is");
            
        double dInterest = 
        	Double.parseDouble(sInterest);
        
        String sYears = 
        	(String)JOptionPane.showInputDialog(null, "years");
        	
        double dYears = 
        	Double.parseDouble(sYears);
        
        
	double dInterestOverTime = 
		dYears * dInterest * dDollars;
	
	
	//Indent block
	if ( dInterestOverTime > 0.0 ) {//I use 0.0 because that is a double. where as 0 is an integer
				
		//Indent blocks of code that are conditional or interative.
		//Indent block
		StringBuffer sbDisplay = new StringBuffer("A loan for ")
				.append( sDollars).append(" dollars, over ")
				.append( sYears ).append("years, at a rate of ")
				.append( sInterest ).append( " percent will cost ")
				.append(dInterestOverTime)
				.append("dollars.");

		//Same level of indent
		//this is a loop that will display a sentences like
		//"A loan for 8 dollars, over 10 years, at a rate of 2 percent will cost your left arm."
		for (int i = 0; i < 3; i++  ) {
			//New indent block.
			System.out.println( sbDisplay.toString() );
		}
	}
	
    }

}
First of all you are putting { } where they don't belong.
Second of all your indenting is bizzare.

Take another look at "code blocks" we don't put { } just for the hell of it.

Funking Giblet
Jun 28, 2004

Jiglightful!
Never mind, thought that was a quote!

Pesch
Nov 4, 2006
Wholly Chao
Is there a platform independent way to open a text file using the default system text editor?

Barring that, how difficult would it be to set up some swing components to display text files? I have very little experience with GUI programming or Swing.

1337JiveTurkey
Feb 17, 2005

Pesch posted:

Is there a platform independent way to open a text file using the default system text editor?

Barring that, how difficult would it be to set up some swing components to display text files? I have very little experience with GUI programming or Swing.

java.awt.Desktop supports browse(), edit(), mail(), open() and print().

The Swing component you're looking for is called JTextArea. The simplest way to put data into it would be to use the default backing Document and then repeatedly append() lines from a file to the end. That works up to several megabytes. If the file's too big for that, Document does support alternative backing methods like just mapping a file into memory and using that as the Document model. That's probably far more difficult than most people would care to implement.

Rabbi Dan
Oct 26, 2005

ASK ME ABOUT MY CREEPY FACEBOOK APP FOR STALKING GIRLS I DON'T KNOW
there is a recommendation in one of my assignment guidelines that i use the java debugger "jdb" but i can't figure out where it is.

it's definitely not in my jre/bin directory where java.exe is, but everything i find on it online says "just type jdb instead of java at the command line" and whenever I do that i get the not recognized command alert.

i'm using winXP.

can anyone help me get jdb running? i'd appreciate it a ton.

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

Rabbi Dan posted:

there is a recommendation in one of my assignment guidelines that i use the java debugger "jdb" but i can't figure out where it is.

it's definitely not in my jre/bin directory where java.exe is, but everything i find on it online says "just type jdb instead of java at the command line" and whenever I do that i get the not recognized command alert.

i'm using winXP.

can anyone help me get jdb running? i'd appreciate it a ton.

jdb should install in the same place as java and javac. If it didn't then you didn't get the JDK and you only got the JRE or some other poo poo that isn't the JDK.

Crepthal
Sep 27, 2005
It's been about a year since I've coded in anything and I'm looking for a book or something that could give me a good Java refresher and then go into some OOP.
If there's something out there that I could read that would give me both of those and perhaps start out on some game development that would be great. Any ideas would be very much appreciated.

sonic bed head
Dec 18, 2003

this is naturual, baby!
I have a jsp with a menu bar that is being <jsp:included> into many other pages. The menu bar is simple, just a list with "Home", "Join", "Contact" and other things like that. I want to know what the best way is to underline the name of the current page without splitting up the jsp that holds the menu, in case something needs to change. I am using struts in case that changes anything. I know that I can send a parameter using the include, but I don't know how best to use that parameter to control "text-decoration:underline." Thanks.

Adbot
ADBOT LOVES YOU

the onion wizard
Apr 14, 2004

sonic bed head posted:

I know that I can send a parameter using the include, but I don't know how best to use that parameter to control "text-decoration:underline." Thanks.

Your best bet would probably be to add a css class of some sort.

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