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
Chairman Steve
Mar 9, 2007
Whiter than sour cream

Chinapwns posted:

Why do people use arrays? This might sound stupid but it seems to me that ArrayLists are better in pretty much every way.

You'll see char arrays used to store passwords (rather than String objects) because it's always passed by reference and is mutable (Strings are not the latter). This allows the password to be zeroed out when it's no longer needed, which prevents the password from being potentially dumped out as part of a heap dump. But, yeah, starting with Java 5, there's rarely a good reason to use an array over a List implementation.

For what it's worth, I hope nothing you write is explicitly returning an ArrayList. You should always return a List reference, as that gives you the freedom to use whatever implementation of the List interface that you want without having to worry about passivity issues.

Adbot
ADBOT LOVES YOU

Fly
Nov 3, 2002

moral compass

Chairman Steve posted:

You'll see char arrays used to store passwords (rather than String objects) because it's always passed by reference and is mutable (Strings are not the latter). This allows the password to be zeroed out when it's no longer needed, which prevents the password from being potentially dumped out as part of a heap dump.
I can't believe I've never considered that.

edit: That would be difficult to implement in a web application unless the front end framework supported use of char arrays.

Fly fucked around with this message at 15:53 on Sep 10, 2010

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

Fly posted:

I can't believe I've never considered that.

edit: That would be difficult to implement in a web application unless the front end framework supported use of char arrays.

Yeah, it's a pretty big deal actually.

It's trivial to pull passwords out of running java apps which is why their physical security is important. If you look at any of the javax.crypto classes, using PBE always requires you to pass in a char [] as the password.

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

Yeah, it's a pretty big deal actually.

It's trivial to pull passwords out of running java apps which is why their physical security is important. If you look at any of the javax.crypto classes, using PBE always requires you to pass in a char [] as the password.
Also Swing JPasswordField recommends the use of char[] getPassword() and zeroing out when done instead of String getText() for the same reason.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Alternatively, you could use Reflections to modify the underlying character array within a String object. :downs:

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?
I'm having trouble getting integer values from a byte buffer filled with signed 16 bit little endian audio samples. I am getting it mostly right, as strange as it sounds, but I'm getting little spikes in my data that look like this...



The spikes have a difference with the rest of the curve of 256, 2^8 so I know that a I'm loving up my bits somewhere.

This problem has been found and explained in this thread, however their solutions do not work for me.
http://forums.sun.com/thread.jspa?threadID=5420508

These are methods I have tried, they all result in the same type of noise being introduced into my output.
code:
byte[] rawInBuffer = new byte[(int)numBytes];
int read = audioInputStream.read(rawInBuffer, 0, rawInBuffer.length);
System.out.println("num bytes read: " + read);
			
int[] returning = new int[(int)numSamples]; 
for (int i = 0, k = 0; i < numSamples - 1; i++)
{			
    byte firstByte = rawInBuffer[++k];
    byte secondByte = rawInBuffer[++k];

    int low = secondByte & 0xff;
    int high = firstByte;
    int returning[i] = (high << 8 | low);
}
code:
byte[] rawInBuffer = new byte[(int)numBytes];
int read = audioInputStream.read(rawInBuffer, 0, rawInBuffer.length);
System.out.println("num bytes read: " + read);
			
int[] returning = new int[(int)numSamples]; 
for (int i = 0, k = 0; i < numSamples - 1; i++)
{			
    ByteBuffer byteBuff = ByteBuffer.allocate(2);
    byteBuff.order(ByteOrder.LITTLE_ENDIAN);
				
    byte firstByte = rawInBuffer[++k];
    byte secondByte = rawInBuffer[++k];
    byteBuff.put(secondByte);
    byteBuff.put(firstByte);
				
    returning[i] = (int) byteBuff.getShort(0);
}
code:
byte[] rawInBuffer = new byte[(int)numBytes];
int read = audioInputStream.read(rawInBuffer, 0, rawInBuffer.length);
System.out.println("num bytes read: " + read);
			
int[] returning = new int[(int)numSamples]; 
for (int i = 0, k = 0; i < numSamples - 1; i++)
{			
   byte firstByte = rawInBuffer[++k];
   byte secondByte = rawInBuffer[++k];


   int d = 0;
   for (int j = 0; j < 8; j++) 
   {
       if (((secondByte >>> j) & 1) == 1) 
       {
           d += (int) Math.pow(2, j);
       }
   }
   for (int j = 0; j < 7; j++) 
   {
       if (((firstByte >>> j) & 1) == 1) 
       {
           d += (int) Math.pow(2, j+8);
       }
   }
   if (((firstByte >>> 7) & 1) == 1) 
   {
       d -= Math.pow(2, 15);
   }
				
    returning[i] = (int) d;
}
Excuse the formatting and if any of that doesn't compile I had to make a few minor changes to cleanly separate that from my code. I know the problem has to do with the samples being signed, the sign bit is loving me up. What is the best way to take the value of the same, sign bit included, without being a douche about it?

Edit: Ended up writing my own wav file processor and reading the samples straight out of the file instead of relying on audioInputStream.read(). Oh well, at least it works.

Kaltag fucked around with this message at 16:28 on Sep 14, 2010

inklesspen
Oct 17, 2007

Here I am coming, with the good news of me, and you hate it. You can think only of the bell and how much I have it, and you are never the goose. I will run around with my bell as much as I want and you will make despair.
Buglord

Kaltag posted:

I'm having trouble getting integer values from a byte buffer filled with signed 16 bit little endian audio samples.

Is there a reason you're not just switching the ByteBuffer's order into little-endian and then just getting a ShortBuffer view of it and reading straight from that? Short is Java's signed 16-bit integer type, after all.

Fly
Nov 3, 2002

moral compass

inklesspen posted:

Is there a reason you're not just switching the ByteBuffer's order into little-endian and then just getting a ShortBuffer view of it and reading straight from that? Short is Java's signed 16-bit integer type, after all.
He might want the 16 bit values to be unsigned, which would require using a larger type than short or Short.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

Fly posted:

He might want the 16 bit values to be unsigned, which would require using a larger type than short or Short.

In that case he could use a CharBuffer. Char is Java's unsigned 16-bit integer type, after all. :v:

Jewbert Jewstein
Dec 4, 2007

Bring me a hard copy of the Internet so I can do some serious surfing
I'm at work right now and I'm working on pulling some data from Google Maps using their geocoding API. When I enter a url (example: http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false) it displays a page written in xml format. How do I extract data from this using java? Specifically I'm looking for the formatted address and the lat/long coordinates.

Any help at all would be much appreciated.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Jewbert Jewstein posted:

I'm at work right now and I'm working on pulling some data from Google Maps using their geocoding API. When I enter a url (example: http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false) it displays a page written in xml format. How do I extract data from this using java? Specifically I'm looking for the formatted address and the lat/long coordinates.

Any help at all would be much appreciated.

Read it in and use XPath to get what you want out of it.

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

Jewbert Jewstein posted:

I'm at work right now and I'm working on pulling some data from Google Maps using their geocoding API. When I enter a url (example: http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false) it displays a page written in xml format. How do I extract data from this using java? Specifically I'm looking for the formatted address and the lat/long coordinates.

Any help at all would be much appreciated.

If you can use groovy at all it's really pitifully easy:
code:
def doc = new XmlParser().parse(new File('geocode.xml'))
def loc = doc.depthFirst().location
println "(${loc.lat.text()}, ${loc.lng.text()})"

Jewbert Jewstein
Dec 4, 2007

Bring me a hard copy of the Internet so I can do some serious surfing

osama bin diesel posted:

Read it in and use XPath to get what you want out of it.

OK, but how do I get the results to change from just a bunch of text in my browser to an xml file that I can use XPath on?

Mill Town
Apr 17, 2006

Jewbert Jewstein posted:

OK, but how do I get the results to change from just a bunch of text in my browser to an xml file that I can use XPath on?

Open the URL in Java instead of your browser :v:

http://download.oracle.com/javase/tutorial/networking/urls/readingURL.html

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Well that depends how you are accessing the data. If you are accessing it inside a program make a URL object out of it and open a stream to it and feed the stream into DocumentBuilder (iirc). If you just want to save what is in your browser go to file and save as.

Jewbert Jewstein
Dec 4, 2007

Bring me a hard copy of the Internet so I can do some serious surfing
Worked! Thanks guys!

Chairman Steve
Mar 9, 2007
Whiter than sour cream
If you ever need to do anything beyond a simple URL (POST parameters, and possibly even for a URL with a query string), Apache's HttpClient library is pretty durn nice: http://hc.apache.org/httpclient-3.x/

HKBGUTT
May 7, 2009


Im rather new to Java so can anybody help we out with this problem:

I want to take 100 random generated numbers (from 1 to 6) from a array and count the times each number occurs without using any if statements or switch statements anywhere.

Basically where i am at now i have created a two dimensional array that sort each numbers into coloumns like this:
code:
		int kast[][];
		kast = new int[7][25];
		Random generator = new Random();
		int z = 0;

		for(int i = 1; i < 7; i++) {
			for(int j = 0; j < 20; j++) {
				z = generator.nextInt(6) + 1;
				kast[z][j] = z;
			}
		}
Unforutnately as you can see this will not allow you to genrerete exactly 100 throws, i don't really know that much of the Java API, but it seems that ArrayList might be useful in this, but im not really certain how to use it, especially for 2 dimensional arrays. I should also note that the sollution should be somewhat elegant, so using forexample alot of nested while and for loops is not really what im after. (Foreaxmple using 6 while loops that checks each number)

So any tips?

HKBGUTT fucked around with this message at 12:47 on Sep 26, 2010

Max Facetime
Apr 18, 2009

You're trying to do it all at once. Break down the problem to smaller pieces, do one piece at a time and print out each piece's internal values to make sure they are what you intended.

Sereri
Sep 30, 2008

awwwrigami

I am in posted:

You're trying to do it all at once. Break down the problem to smaller pieces, do one piece at a time and print out each piece's internal values to make sure they are what you intended.

OR ||

code:
		int kast[] = new int[6];
		Random generator = new Random();
		int z;

		for(int i = 0; i < 100; i++) {
				z = generator.nextInt(6);
				kast[z]++;
		}
I think you are over-complicating it. Do you actually need to save the numbers? Probably not.

HKBGUTT
May 7, 2009


Well i need to the following things:

1)Print all the numbers.
2)Find the average of all the numbers.
3)Find the number that occured the most.
4)Measure how long before the number '6' was generated.
5)Never use IF or SWITCH.

So i need to save all the numbers somehow.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

HKBGUTT posted:

Well i need to the following things:

1)Print all the numbers.
2)Find the average of all the numbers.
3)Find the number that occured the most.
4)Measure how long before the number '6' was generated.
5)Never use IF or SWITCH.

So i need to save all the numbers somehow.

How are you going to test for whether a number is a six without using if or some horrible hack?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Hey, now- the ternary operator isn't necessarily a horrible hack.

Depending on how that list of output needs to be returned, you still don't necessarily need to store all the numbers.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
But you can easily translate any one-way conditional statement into a for-loop, to get around the "don't use an if" restriction:

code:
if (condition) {
    // body
}
code:
for (boolean stop = false; condition && !stop; stop = true) {
    // body
}
:haw:

Sorry, I thought this was the Coding Horrors thread for a second.

HKBGUTT
May 7, 2009


Yeah it is a school asignment, and the asignment says: Dont use If or Switch for some reason. And it also specifies that the random numbers must be added to a array.

Max Facetime
Apr 18, 2009

Jonnty posted:

How are you going to test for whether a number is a six without using if or some horrible hack?

Use a state-machine!

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

HKBGUTT posted:

Yeah it is a school asignment, and the asignment says: Dont use If or Switch for some reason. And it also specifies that the random numbers must be added to a array.

Ah. Presumably they're doing the "we want to teach these concepts by forcing you to use then for a problem where they don't actually belong" thing programming courses like to do.

Sereri
Sep 30, 2008

awwwrigami

HKBGUTT posted:

Yeah it is a school asignment, and the asignment says: Dont use If or Switch for some reason. And it also specifies that the random numbers must be added to a array.

use while(), be all :smug:

HKBGUTT
May 7, 2009


Yeah, so far the only sollution i've found is to use some horrible combinations of while and for loops but it really looks terrible. Elegance is not specifically required in this task, but still.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
This isn't tested, but this should get you going:
code:
        int randomNumbers = 100;
        int[] generatedNumbers = new int[randomNumbers];
        int[] most = new int[6];
        Random generator = new Random();
        for (int i = 0; i < randomNumbers; i++){
                int number = generator.nextInt(6);
                most[number]++;
                generatedNumbers[i] = number+1;
        }

        int firstSix = 0;
        int number = 0;
        for (int i = 0; number != 6 && i < randomNumbers; i++){
                number = generatedNumbers[i];
                firstSix = i;
        }
        List mostOcurrences = Arrays.asList(most);
        Collections.sort(mostOcurrences);
        int mostOcurred = (Integer)mostOcurrences.get(0);

Vergeh
Jan 15, 2008

Pockets!
I have a very specific problem. I have a java program that monitors an executable's PID (well, actually it monitors the javaw.exe launched by this parent executable, so I can't get it by any conventional means I've come across). The program sleeps in a loop until that PID disappears.

Up until now, I've been using a Runtime exec call to tasklist.exe and parsing its output. The problem is that tasklist is not a native executable in Home versions of Windows (and the other problem, naturally, is that this program will only work on windows).

Is there a way to call up a master list of processes and subprocesses natively in Java? I'm not averse to installing custom packages.

Max Facetime
Apr 18, 2009

Vergeh posted:

Is there a way to call up a master list of processes and subprocesses natively in Java? I'm not averse to installing custom packages.

If you're using Sun's JDK 1.5 or newer then there is a native executable called jps that lists all Java processes.

It seems jps is implemented at least partially in Java, so you might be able to use its source code as a guide. It's located in package sun.tools.jps, I think.

StickFigs
Sep 5, 2004

"It's time to choose."
I'm trying to use a StringTokenizer and I need it to count anything that isn't a character of the regular alphabet as a delimiter, for example:

"the, thr3e people."

will result in:

the
thr
e
people

Is there an easy way to set up this delimiter besides manually typing in every single possible non-alphabetic character?

Sereri
Sep 30, 2008

awwwrigami

StickFigs posted:

I'm trying to use a StringTokenizer and I need it to count anything that isn't a character of the regular alphabet as a delimiter, for example:

"the, thr3e people."

will result in:

the
thr
e
people

Is there an easy way to set up this delimiter besides manually typing in every single possible non-alphabetic character?

Sound like something regular expressions were made for.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Does anyone know of a solid library for parsing/tokenizing java sourcecode? I'm dealing with some hairy code generation/emission stuff related to a test framework, and I really don't like the idea of simply tossing some regular expressions at the problem.

Ideally, I'd like to be able to just walk through an AST and identify expressions so I can add logic to deal with some new operators and semantics.

StickFigs
Sep 5, 2004

"It's time to choose."

Sereri posted:

Sound like something regular expressions were made for.

Where would I find a list of regular expressions useful to my situation?

Mr.Radar
Nov 5, 2005

You guys aren't going to believe this, but that guy is our games teacher.

Internet Janitor posted:

Does anyone know of a solid library for parsing/tokenizing java sourcecode? I'm dealing with some hairy code generation/emission stuff related to a test framework, and I really don't like the idea of simply tossing some regular expressions at the problem.

Ideally, I'd like to be able to just walk through an AST and identify expressions so I can add logic to deal with some new operators and semantics.

ANTLR, a parser generator for Java, has a grammar for parsing Java 1.5 as one of its examples. It's not the easiest program to work with, but it should be able to do what you want.

Sereri
Sep 30, 2008

awwwrigami

StickFigs posted:

Where would I find a list of regular expressions useful to my situation?

I'd combine this and this

The regex in case should be [a-zA-Z]

/E:

JavaDoc posted:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Sereri fucked around with this message at 21:51 on Sep 27, 2010

Mayheim
Jun 15, 2006
I have been looking far and wide for a Math resource to use with Java Micro Edition.
There seems none to be found that provides sinh() and atan(), or even just exp() and pow() to build the formulars myself.

Edit:
To be specific, I need to make this work in Java Micro Edition
code:
double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z); 
return Math.toDegrees(Math.atan(Math.sinh(n))); 
Edit Edit:
This mostly sorted itself out.
Jave ME's Math-class not having exp(), pow() and log() kinda blows, thought.

Mayheim fucked around with this message at 12:47 on Sep 28, 2010

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

Here's really candid interview with James Gosling - some interesting tidbits, including a bit about microSPARC that was a touchscreen LCD in the early 90s - which the people leading that were heavily involved with the iPad later.


http://basementcoders.com/?p=721

http://www.basementcoders.com/transcripts/James_Gosling_Transcript.html

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