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
Flamadiddle
May 9, 2004

MEAT TREAT posted:

This is the correct way to do it, you don't want random people on the internet to have direct access to your database.

Yeah, I figured as much. I'm new to Java anyway, and so far have had to learn HTTP pushes and JDBC connections. I guess I'll need to learn about opening socket connections and such?

Adbot
ADBOT LOVES YOU

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

Flamadiddle posted:

Yeah, I figured as much. I'm new to Java anyway, and so far have had to learn HTTP pushes and JDBC connections. I guess I'll need to learn about opening socket connections and such?

This is pretty much exactly what web services are meant to do. Secure, abstracted, simple (for various values of simple).

1337JiveTurkey
Feb 17, 2005

TRex EaterofCars posted:

This is pretty much exactly what web services are meant to do. Secure, abstracted, simple (for various values of simple).

If it's some practice toy app for fun running on a local network, there's nothing wrong with just opening a socket to the server and passing serialized objects for messages.

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

1337JiveTurkey posted:

If it's some practice toy app for fun running on a local network, there's nothing wrong with just opening a socket to the server and passing serialized objects for messages.

I agree. Maybe I misunderstood but he used the word "staff" so I figured this would be production.

Flamadiddle
May 9, 2004

Yeah, it's actually for work (a university). It's a system we're planning on opening up to staff so they can text their students in the event that they can't make a lecture or tutorial, so they need to be able to access it from home.

I'm thinking I'll build a server side application that does all the populating of data from the database before sending the message. My applet will just be a GUI for people to enter the message and that'll just get passed to the server.

There's authentication and stuff on a couple of levels (within the DB and with the SMS provider) but you obviously need to pass a username/password to the database, so it's probably better that that all sits on the server side application, rather than floating around in some public .jar file.

Thanks for the advice.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Flamadiddle posted:

My applet will just be a GUI for people to enter the message and that'll just get passed to the server.

Honestly a simple html form is all you need. No need to even make an applet.

Flamadiddle
May 9, 2004

MEAT TREAT posted:

Honestly a simple html form is all you need. No need to even make an applet.

My HTML isn't up to my Java, which isn't up to much. How would you even get an HTML form to submit to the server-side application? With an HTTP Get or something?

icehewk
Jul 7, 2003

Congratulations on not getting fit in 2011!
I'm doing the 'create a payroll program' assignment and having some trouble with the 'double' lines.

Here's what I've got so far:

code:
import java.text.*;
import java.util.*;

public class Payroll {


    public static void main(String[] args)
    {
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = "";

		System.out.print("Enter employee's name: ");
				input = in.readLine();
				String name = new String(input);

		System.out.print("Enter hours worked in a week: ");
				input = in.readLine();
				String hours = new String(input);

		System.out.print("Enter hourly pay rate: ");
				input = in.readLine();
				String payrate = new String(input);

		System.out.print("Enter federal tax withholding rate: ");
				input = in.readLine();
				String fed = new String(input);

		System.out.print("Enter state tax rate: ");
		input = in.readLine();
		String state = new String(input);

		DecimalFormat df = new DecimalFormat("0.00");

		Scanner scan = new Scanner(System.in);

        System.out.print("Hours worked: 	"+ hours);
        System.out.print("Pay Rate: 		$" + rate);

        double gross = ( rate.doubleValue() * hours.doubleValue();
        System.out.print("Gross Pay:		$" + df.format(gross);

        double taxfed = ( fed.doubleValue() * gross.doubleValue();
        double taxstate = ( state.doubleValue() * gross.doubleValue();
        double taxnet = ( taxfed.doubleValue() + taxstate.doubleValue();

        System.out.println("Deductions:"
        	+ "\n\n"
        	+ "Federal Withholding <20.0%>:			$" + df.format(taxfed) 	+ "\n"
        	+ "State Withholding <9.0%>:			$" + df.format(taxstate) 	+ "\n"
        	+ "Total Deduction:						$" + df.format(taxnet));

		System.out.println("Net Pay:		$" + ( gross - taxnet ));


    }

}

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
If you look at the String API, you'll see that there is no such method as doubleValue(). What you need to do is use the Double class to parse your strings like so.
code:
double taxfed = ( Double.parseDouble(fed) * Double.parseDouble(gross) );

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
MEAT TREAT got to the bit about parsing doubles before I could, so I'm going to go off on a total tangent, because you seem to be confused about variables. Clearing that up won't fix your problem, but it's important if you're going to do anything.

icehewk posted:

code:
	System.out.print("Enter hours worked in a week: ");
	input = in.readLine();
	String hours = new String(input);

In Java, a variable of object type (i.e. a variable that's not of type int, char, boolean, double, etc. --- note that these are all lower case) holds a reference to an object. If you've got two different variables, that means you've got two different references, but there's nothing saying that the references can't be to the same object.

So suppose you type in "48.5" on this line; in.readLine() will return a String object with data "48.5", and then we assign a reference to that object to the variable 'input', so that memory looks like this:
code:
input  -->  String "48.5"
The next line asks for a new String object with the same data as the one currently referenced by 'input', so after that line, memory looks like this:
code:
input  -->  String "48.5"
hours  -->  String "48.5"
Now, sometimes there's a good reason to copy whole objects like that: for example, it might be a modifiable list, and I might want to remember what it looks like right now. But String objects can never be modified, so there's really no reason to copy them, at least not that most people ever need to care about. So instead of copying the String object, all you really need to do is copy the reference like so:
code:
        hours = input;
which will produce memory like this:
code:
input   -->  String "48.5"
hours   --------^^^
And note that it's okay to assign a new reference to 'input'; hours doesn't care what's in 'input' anymore, it just has this reference to a String object. So if I go on to the next bit in your program (rewritten to not copy objects), and the user typed in 17.9, I'd get:
code:
input   -->  String "17.9"
fed     --------^^^
hours   -->  String "48.5"
In fact, you don't even need the variable 'input' anymore, you can just directly assign the output of in.readLine() direct to the variable you want.

icehewk
Jul 7, 2003

Congratulations on not getting fit in 2011!
I'm having quite a bit of trouble, could you hit me up on AIM? icehewk

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Flamadiddle posted:

My HTML isn't up to my Java, which isn't up to much. How would you even get an HTML form to submit to the server-side application? With an HTTP Get or something?

What kind of webserver are you running? Honestly it sounds like java is over kill if all you need is a interface to get data into the database. I would consider just a PHP or a CGI page in perl or something to handle it. Should be able to find a tutorial online for either of those very easily.

To use a HTML you will need a Java application server (Tomcat/Jetty/GlassFish etc) as far as I know. From there it would be easier to write a JSP page. There are other ways of course, HttpServletRequest allows you to read GET data via getParameter(String). It's not a bad idea to set up an app server if you plan to write some more web apps but a little overkill for this project. If you run Apache then setting it up to forward the correct stuff to Tomcat isn't that hard, with IIS it is a little more difficult but doable.

Again, I don't think Java is the correct tool for the job here. PHP or a CGI script can open up the database handle you need and keep everything on the server side.

Flamadiddle
May 9, 2004

dvinnen posted:

What kind of webserver are you running? Honestly it sounds like java is over kill if all you need is a interface to get data into the database. I would consider just a PHP or a CGI page in perl or something to handle it. Should be able to find a tutorial online for either of those very easily.

To use a HTML you will need a Java application server (Tomcat/Jetty/GlassFish etc) as far as I know. From there it would be easier to write a JSP page. There are other ways of course, HttpServletRequest allows you to read GET data via getParameter(String). It's not a bad idea to set up an app server if you plan to write some more web apps but a little overkill for this project. If you run Apache then setting it up to forward the correct stuff to Tomcat isn't that hard, with IIS it is a little more difficult but doable.

Again, I don't think Java is the correct tool for the job here. PHP or a CGI script can open up the database handle you need and keep everything on the server side.

Thanks for that. We're discussing the merits of all the options at the moment. I'll have a word with our Perl guy and see what he thinks about building the page. I think we're on IIS but I'd have to check.

icehewk
Jul 7, 2003

Congratulations on not getting fit in 2011!
I'm still getting a 'few' errors. I think I'm missing something from the beginning

code:
import java.text.*;
import java.util.*;

public class Payroll {


    public static void main(String[] args)
    {
		System.out.print("Enter employee's name: ");
				Input = In.readLine();
				name = input;

		System.out.print("Enter hours worked in a week: ");
				hours = in.readLine();

		System.out.print("Enter hourly pay rate: ");
				payrate = in.readLine();

		System.out.print("Enter federal tax withholding rate: ");
				fed = in.readLine();

		System.out.print("Enter state tax rate: ");
				state = in.readLine();

		DecimalFormat df = new DecimalFormat("0.00");

		Scanner scan = new Scanner(System.in);

        System.out.print("Hours worked: 	"+ Hours);
        System.out.print("Pay Rate: 		$" + Rate);

       double gross = ( Double.parseDouble(rate) * Double.parseDouble(hours) );
        System.out.print("Gross Pay:		$" + (gross));

       double taxfed = ( Double.parseDouble(fed) * Double.parseDouble(gross) );
       double taxstate = ( Double.parseDouble(state) * Double.parseDouble(gross) );
       double taxnet = ( Double.parseDouble(taxfed) + Double.parseDouble(taxstate) );

        System.out.println("Deductions:"
        	+ "\n\n"
        	+ "Federal Withholding <20.0%>:			$" + df.format(taxfed) 	+ "\n"
        	+ "State Withholding <9.0%>:			$" + df.format(taxstate) 	+ "\n"
        	+ "Total Deduction:						$" + df.format(taxnet));

		System.out.println("Net Pay:		$" + (gross - taxnet));


    }

}
code:
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:10: cannot find symbol
symbol  : variable Input
location: class Payroll
				Input = In.readLine();
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:10: cannot find symbol
symbol  : variable In
location: class Payroll
				Input = In.readLine();
				        ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:11: cannot find symbol
symbol  : variable name
location: class Payroll
				name = input;
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:11: cannot find symbol
symbol  : variable input
location: class Payroll
				name = input;
				       ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:14: cannot find symbol
symbol  : variable hours
location: class Payroll
				hours = in.readLine();
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:14: cannot find symbol
symbol  : variable in
location: class Payroll
				hours = in.readLine();
				        ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:17: cannot find symbol
symbol  : variable payrate
location: class Payroll
				payrate = in.readLine();
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:17: cannot find symbol
symbol  : variable in
location: class Payroll
				payrate = in.readLine();
				          ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:20: cannot find symbol
symbol  : variable fed
location: class Payroll
				fed = in.readLine();
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:20: cannot find symbol
symbol  : variable in
location: class Payroll
				fed = in.readLine();
				      ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:23: cannot find symbol
symbol  : variable state
location: class Payroll
				state = in.readLine();
				^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:23: cannot find symbol
symbol  : variable in
location: class Payroll
				state = in.readLine();
				        ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:29: cannot find symbol
symbol  : variable Hours
location: class Payroll
        System.out.print("Hours worked: 	"+ Hours);
                                        	   ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:30: cannot find symbol
symbol  : variable Rate
location: class Payroll
        System.out.print("Pay Rate: 		$" + Rate);
                                    		     ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:32: cannot find symbol
symbol  : variable rate
location: class Payroll
       double gross = ( Double.parseDouble(rate) * Double.parseDouble(hours) );
                                           ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:32: cannot find symbol
symbol  : variable hours
location: class Payroll
       double gross = ( Double.parseDouble(rate) * Double.parseDouble(hours) );
                                                                      ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:35: cannot find symbol
symbol  : variable fed
location: class Payroll
       double taxfed = ( Double.parseDouble(fed) * Double.parseDouble(gross) );
                                            ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:35: parseDouble(java.lang.String) in java.lang.Double cannot be applied to (double)
       double taxfed = ( Double.parseDouble(fed) * Double.parseDouble(gross) );
                                                         ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:36: cannot find symbol
symbol  : variable state
location: class Payroll
       double taxstate = ( Double.parseDouble(state) * Double.parseDouble(gross) );
                                              ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:36: parseDouble(java.lang.String) in java.lang.Double cannot be applied to (double)
       double taxstate = ( Double.parseDouble(state) * Double.parseDouble(gross) );
                                                             ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:37: parseDouble(java.lang.String) in java.lang.Double cannot be applied to (double)
       double taxnet = ( Double.parseDouble(taxfed) + Double.parseDouble(taxstate) );
                               ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:37: parseDouble(java.lang.String) in java.lang.Double cannot be applied to (double)
       double taxnet = ( Double.parseDouble(taxfed) + Double.parseDouble(taxstate) );
                                                            ^
C:\Documents and Settings\Chris\Desktop\Homework\Java\Payroll.java:37: incompatible types
found   : java.lang.String
required: double
       double taxnet = ( Double.parseDouble(taxfed) + Double.parseDouble(taxstate) );
                                                    ^
23 errors

Tool completed with exit code 1

lamentable dustman
Apr 13, 2007

🏆🏆🏆

icehewk posted:

I'm still getting a 'few' errors. I think I'm missing something from the beginning


drat dude, I usually like helping people do their homework but you got some serious issues. Lets start with the obvious stuff.

code:
System.out.print("Enter employee's name: "); 
    Input = In.readLine(); 
    name = input;   
Why did you change this? It was actually correct from last night. rjmccall was giving you reasons why you should do it another way because of memory issues.

With the current iteration why did you remove the BufferedReader? You need that to read the input. What is 'Input' suppose to be? You never declared it, nor did you declare 'input'. Java is case sensitive so it sees those as different variables. From the code last night do this.

code:
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 

    System.out.print("Enter employee's name: "); 
    String name = in.readLine();
See? That was what rjmccall was getting at. You never needed the String 'input'. Repeat all the way down.

Later on I notice you are using the variable 'Hours' instead of 'hours'. The variable 'Rate' is also not declared (guess it should be 'payrate').

Next issue are this line:
code:
double taxfed = ( Double.parseDouble(fed) * Double.parseDouble(gross) ); 
Above that line 'gross' was declared to be of type double so you don't need to parse a double out of it.


The above should get it close to compiling I would guess. It is obvious you are new to programming here (CS101?) but you need some help. Does you your school offer CompSci tutoring? If not go spend a few hours in the professors office.

icehewk
Jul 7, 2003

Congratulations on not getting fit in 2011!
It does offer tutoring, when the tutor remembers to show up. Thanks for your help and patience. I'll definitely get the basics down before I post again.


edit: I got it running perfectly thanks to your suggestions and a little error googling. Thanks!

icehewk fucked around with this message at 07:19 on Sep 19, 2008

Blackout
Jun 29, 2005

I am a deathdealer.
edit: I figured it out.

Hey guys, I've got an issue that you might be able to help me with. I'm making a swing-based UI with one JTree and one JList. When an item is selected on the JTree, it updates the JList with a string array based on the value of the item selected in the JTree.

The items in the JList represent test results, and the items in the JTree represent dates on which tests are run. Each date has children for both the test cases run that that day and the failures reported. If the user clicks on the test cases node, the tests cases run that day are shown in the JList, and if they click on the failures node, the failures recieved that day are displayed in the JList.

Now heres where I'm running into my problem. I want to display colors on the rows in the JList when Test Cases are selected. If a test case passed, I want it to be green, and if it failed, red.

I'm using a custom JUnit class called ZebraJList, which displays rows with alternating background colors. I added in a line in the class' ListCellRenderer to adjust the foreground color based on a variable I set from another class. However, my app seems to add all of the data to the JList, and then call the renderer for each row in that JList, rather than adding a row and immediately calling the renderer for it. This means that the entire list is rendered with the last foreground color that was specified, rather than being rendered with the two different colors in different areas.

Hopefully this still makes sense!

Here is the code for the cell renderer, followed by my MouseListener code (Which picks up selections in the JTree and updates the JList)

code:
private class RendererWrapper
        implements javax.swing.ListCellRenderer
    {
        public javax.swing.ListCellRenderer ren = null;
 
        public java.awt.Component getListCellRendererComponent(
            javax.swing.JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus )
        {
            final java.awt.Component c = ren.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus );
            if ( !isSelected && drawStripes )
                c.setBackground( rowColors[index&1] );
            c.setForeground(foregroundColor);
            return c;
        }
    }
    private RendererWrapper wrapper = null;
 
    /** Return the wrapped cell renderer. */
    public javax.swing.ListCellRenderer getCellRenderer( )
    {
        final javax.swing.ListCellRenderer ren = super.getCellRenderer( );
        if ( ren == null )
            return null;
        if ( wrapper == null )
            wrapper = new RendererWrapper( );
        wrapper.ren = ren;
        return wrapper;
    }
code:
MouseListener dateMouseListener = new MouseAdapter() {
	public void mouseClicked(MouseEvent e) {
		if ((e.getClickCount() == 2)&&(e.getButton() == e.BUTTON1)) {
			DefaultMutableTreeNode nodeSelected = (DefaultMutableTreeNode)dateTree.getLastSelectedPathComponent();
			if (!(nodeSelected.getParent() == null)) {	
				if (!(nodeSelected.getParent().toString() == "Result Dates")) {
					String dateSelected = nodeSelected.getParent().toString();
					ArrayList<String> array = null;
					if (nodeSelected.toString() == "Test Cases") {
						array = oqp.getTestsForDate(dateSelected);
						testListModel.clear();
						for (int i=0;i<array.size();i++) {
							if (oqp.TestPassedOnDate(array.get(i), nodeSelected.getParent().toString())) {
								testList.setForegroundColor(java.awt.Color.green);
								}
							else {
								testList.setForegroundColor(java.awt.Color.red);
							}
							testListModel.addElement(array.get(i));
						}
					}
					else if (nodeSelected.toString() == "Failures") {
						array = oqp.getFailuresForDate(dateSelected);
						testListModel.clear();
						testList.setForegroundColor(java.awt.Color.black);
						for (int i=0;i<array.size();i++) {
							testListModel.addElement(array.get(i));
						}
					}
					else return;
				}
			}
		}
	}
Basically my question is how do I get the cell renderer to render each row as it is created, rather than after the entire array of data has been added to the list?

Thanks in advance!

Blackout fucked around with this message at 20:05 on Sep 19, 2008

Blackout
Jun 29, 2005

I am a deathdealer.
Nevermind, I figured it out.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Blackout posted:

Basically my question is how do I get the cell renderer to render each row as it is created, rather than after the entire array of data has been added to the list?

You don't. Swing UIs aren't just drawn once to some sort of static image; they're redrawn repeatedly in response to all sorts of possible user events. At any point in time, you have to be prepared to re-render all or part of the list. As such, you can't rely on precise order of execution like that.

The way JList is designed is that the UI invokes the ListCellRenderer to get a drawing component for each row, passing in whatever arbitrary object was added to the list (which doesn't have to be a string). Generally this is the same component over and over, and the renderer just sets properties on it specific to that row. Since it looks like you're already adding useful objects (i.e. the actual test-case objects) to the list, I would suggest just modifying your ListCellRenderer to 1) check whether the passed-in object is a test case and, if so, 2) change the background color on the rendering component according to whether the test case failed or not.

Boz0r
Sep 7, 2006
The Rocketship in action.
Is there some sort of smart method when I've extracted an array of bytes from a file, to convert them to long, short, or chars in Java?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Boz0r posted:

Is there some sort of smart method when I've extracted an array of bytes from a file, to convert them to long, short, or chars in Java?

What sort of conversion do you have in mind? If you mean "read these bytes according to host-specific encoding conventions", take a look at java.nio.ByteBuffer.

Boz0r
Sep 7, 2006
The Rocketship in action.

rjmccall posted:

What sort of conversion do you have in mind? If you mean "read these bytes according to host-specific encoding conventions", take a look at java.nio.ByteBuffer.

I'm not too hot on programming yet, but doesn't abstract mean the function hasn't been defined?

Otherwise, that class does everything I looked for.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Boz0r posted:

I'm not too hot on programming yet, but doesn't abstract mean the function hasn't been defined?

Otherwise, that class does everything I looked for.

It means that the class doesn't define the methods, yes, and cannot be directly instantiated. In the case of ByteBuffer, that's because there are several interesting implementation-specific subclasses. There are static methods on ByteBuffer (allocate(int), allocateDirect(int), wrap(byte[]), and wrap(byte[],int,int)) which are useful for creating various different kinds of buffer; if you've already got a byte array, you should probably just use wrap.

Boz0r
Sep 7, 2006
The Rocketship in action.

rjmccall posted:

It means that the class doesn't define the methods, yes, and cannot be directly instantiated. In the case of ByteBuffer, that's because there are several interesting implementation-specific subclasses. There are static methods on ByteBuffer (allocate(int), allocateDirect(int), wrap(byte[]), and wrap(byte[],int,int)) which are useful for creating various different kinds of buffer; if you've already got a byte array, you should probably just use wrap.

Ok, but when I've used wrap and gotten a ByteBuffer with the bytes in it, how do I get it out in the different types, as I still can't use the getLong(), getShort()... methods?

the onion wizard
Apr 14, 2004

Boz0r posted:

Ok, but when I've used wrap and gotten a ByteBuffer with the bytes in it, how do I get it out in the different types, as I still can't use the getLong(), getShort()... methods?

wrap and allocate appear to actually return an instance of HeapByteBuffer, which presumably implements those abstract methods.

Boz0r
Sep 7, 2006
The Rocketship in action.

triplekungfu posted:

wrap and allocate appear to actually return an instance of HeapByteBuffer, which presumably implements those abstract methods.

I can't seem to find this HeapByteBuffer anywhere in the API, though.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

What kind of file are you reading from?

Edit: realized I didn't read carefully enough.

lamentable dustman fucked around with this message at 18:52 on Sep 21, 2008

csammis
Aug 26, 2003

Mental Institution

Boz0r posted:

Ok, but when I've used wrap and gotten a ByteBuffer with the bytes in it, how do I get it out in the different types, as I still can't use the getLong(), getShort()... methods?

What do you mean, you can't use the getLong, getShort, etc. methods? Any object returned by wrap or allocate will have those methods defined, even if what it's returning is an instance of the abstract base class. You're not supposed to need to know the precise implementation, HeapByteBuffer or whatever.

teen bear
Feb 19, 2006

For a small project at school we're supposed to round a number to the nearest 5 using Math.ceil().

As far as I can tell ceil just round up to the nearest integer. How can I make it so that it rounds to the nearest 5?

oh no computer
May 27, 2003

Capc posted:

For a small project at school we're supposed to round a number to the nearest 5 using Math.ceil().

As far as I can tell ceil just round up to the nearest integer. How can I make it so that it rounds to the nearest 5?
Divide by 5, call Math.ceil() on that to get an integer, then multiply the result by 5 - this would round up to the nearest 5 (if that was what you meant). If you want to get to the nearest 5 you'd have to use Math.round() instead of Math.ceil().

teen bear
Feb 19, 2006

BELL END posted:

Divide by 5, call Math.ceil() on that to get an integer, then multiply the result by 5 - this would round up to the nearest 5 (if that was what you meant). If you want to get to the nearest 5 you'd have to use Math.round() instead of Math.ceil().

Yes, thank you. That's exactly what I needed.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

If you need to do a round rather then just round up all you have to do is the following.

1) Divide by 5
2) Subtract .5 (cast to double for all this of course)
3) Call the ceiling function.
4) Multiply that by 5.

ex) 24/5 = 4.8 - .5 = ceiling(4.3) = 5 * 5 = 25
ex) 22/5 = 4.4 - .5 = ceiling(3.9) = 4 * 5 = 20

teen bear
Feb 19, 2006

It was just to round up to the nearest nickel when giving change.

I ended up doing it like this:

(Math.ceil((change*100)/5)*5.0)/100.0

Is this the best, or even right, way to be doing this? It seems overly complicated, but it does work.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Capc posted:

(Math.ceil((change*100)/5)*5.0)/100.0

That looks okay to me.

I usually advise people to avoid floating-point representations for fixed-point values like currency, but given that this is an intro-programming assignment, it's probably not worth the effort. If you get weird one-off errors, though, that's where it's coming from.

Boz0r
Sep 7, 2006
The Rocketship in action.
Is there an easy way to insert the contents of an array into another array?

I have two arrays:
int[] mapSignature = new int[4];
int[] mapVersion = new int[2];

Which I want to be the first 6 entries in a new array:

int[] header = new int[22];

is there any way around making for loops to insert them?

Alan Greenspan
Jun 17, 2001

Boz0r posted:

is there any way around making for loops to insert them?

There is System.arraycopy.

Boz0r
Sep 7, 2006
The Rocketship in action.

Alan Greenspan posted:

There is System.arraycopy.

You, sir, are of high moral fiber.

Is it possible to assign the same value to two different destinations at the same time, like:

i=j=4;

or something?

Boz0r fucked around with this message at 23:15 on Sep 22, 2008

csammis
Aug 26, 2003

Mental Institution

Boz0r posted:

You, sir, are win.

Really? :crossarms:

quote:

Is it possible to assign the same value to two different destinations at the same time, like:

i=j=4;

or something?

Try it and see if a compiler error results. Should work just fine

Boz0r
Sep 7, 2006
The Rocketship in action.

csammis posted:

Really? :crossarms:

Well, he knows more Java than me, so by that definition, most people in this thread are high moral fiber.

csammis posted:

Try it and see if a compiler error results. Should work just fine

Hey, what do you know, it works.

Boz0r fucked around with this message at 23:16 on Sep 22, 2008

Adbot
ADBOT LOVES YOU

csammis
Aug 26, 2003

Mental Institution

Boz0r posted:

Well, he knows more Java than me, so by that definition, most people in this thread are win.

What I meant was, didn't calling something "win" used to be probatable?

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