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
Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Volguus posted:

And lombok doesn't process the source code, it processes the AST and the bytecode. The AST you get after the syntax analysis phase, and the bytecode after the actual compilation. The actual source code has been processed already, only after that lombok itself kicks in. This, therefore, does not meet your definition of a pre-processor.

There's an implementation that is literally a preprocessor (unless you want to argue that delombok somehow isn't one?). To me, that's sufficient to call the project a preprocessor even if there are alternate implementations that use a different mechanism to achieve the same thing.

Adbot
ADBOT LOVES YOU

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

Volguus posted:

And lombok doesn't process the source code, it processes the AST and the bytecode. The AST you get after the syntax analysis phase, and the bytecode after the actual compilation. The actual source code has been processed already, only after that lombok itself kicks in. This, therefore, does not meet your definition of a pre-processor.

Cool, it has a postprocessing step too.

TheresaJayne
Jul 1, 2011

foonykins posted:

This is precisely where I'm hung up. Would another set of copies solve this issue? Would it, in sorts, work a kind of save-state when the method is called again?

Also, in terms of IDEs, im using NetBeans. I've never worked with a debugger before. I've heard great things about IntelliJ Idea but was having a hard time configuring it on my Mac. All that talk is for the IDE thread though.

Maybe not the solution, but one thing that makes me feel you are not doing it in the best solution, How are you determining the no repetitions?

The moment I hear no repetitions I start looking at Map HashMap to be precise. as Maps cannot have duplicate keys.and you could also store the nnumber of times the item is seen in the value if needed.

I will admit i an half asleep here just relaxing before heading to bed.

JimboMaloi
Oct 10, 2007

Volmarias posted:

And to follow up, if you're allowed to for homework, you should just use StringBuilder. A typical novice mistake for java is to do what you're doing, which is to build a string by appending to an accumulator string over and over, since that involves creating a new builder and a new immutable string in every single round of your loop.

It's worth noting (for someone still learning the difference) that this is only really true in the case where you have a loop. I've frequently seen it get cargo culted to every time strings are being concatenated.

code:
String foo = "Bar" + baz + "qux" + butts;
is, so far as any Java compiler you're likely to encounter in the wild is concerned, going to end up being the exact same bytecode as
code:
StringBuilder builder = new StringBuilder();
builder.append("Bar");
builder.append(baz);
builder.append("qux");
builder.append(butts);
String foo = builder.toString();
To be honest I also might argue against concerning yourself with the performance gains of using StringBuilder in a loop until you know you need it, but that's more personal preference.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

JimboMaloi posted:

To be honest I also might argue against concerning yourself with the performance gains of using StringBuilder in a loop until you know you need it, but that's more personal preference.

I'd argue the opposite; it's good practice always to use it in a loop (unless you have given your loop a very short, very explicit duration, e.g. i = 0-2), in recursive calls, etc, since you can't guarantee that your mock up code won't end up being permanent and with a vastly increased scope.

It's only a little extra work to do it, and you're doing it right.

dr cum patrol esq
Sep 3, 2003

A C A B

:350:
Is there a rule of thumb or best practice on how much code to put in an actionlistener?

FateFree
Nov 14, 2003

dev null posted:

Is there a rule of thumb or best practice on how much code to put in an actionlistener?

The smallest amount needed to complete your task. But that goes for any method.

hooah
Feb 6, 2006
WTF?
I'm trying to build and run jMAVSim. When I tried to build the project in IntellliJ IDEA under Java 1.8.0_31, I get these errors:

quote:

F:\jMAVSim\jMAVlib\src\me\drton\jmavlib\conversion\RotationConversion.java
Error:(3, 23) java: cannot find symbol
symbol: class Matrix
location: package org.la4j.matrix
Error:(13, 19) java: cannot find symbol
symbol: class Matrix
location: class me.drton.jmavlib.conversion.RotationConversion
Error:(14, 9) java: cannot find symbol
symbol: class Matrix
location: class me.drton.jmavlib.conversion.RotationConversion
F:\jMAVSim\src\me\drton\jmavsim\SerialMAVLinkPort.java
Error:(80, 18) java: constructor MAVLinkStream in class me.drton.jmavlib.mavlink.MAVLinkStream cannot be applied to given types;
required: me.drton.jmavlib.mavlink.MAVLinkSchema,java.nio.channels.ByteChannel
found: me.drton.jmavlib.mavlink.MAVLinkSchema
reason: actual and formal argument lists differ in length
Error:(102, 23) java: method write in class me.drton.jmavlib.mavlink.MAVLinkStream cannot be applied to given types;
required: me.drton.jmavlib.mavlink.MAVLinkMessage
found: me.drton.jmavlib.mavlink.MAVLinkMessage,java.nio.channels.ByteChannel
reason: actual and formal argument lists differ in length
Error:(114, 29) java: method read in class me.drton.jmavlib.mavlink.MAVLinkStream cannot be applied to given types;
required: no arguments
found: java.nio.channels.ByteChannel
reason: actual and formal argument lists differ in length
F:\jMAVSim\src\me\drton\jmavsim\UDPMavLinkPort.java
Error:(32, 18) java: constructor MAVLinkStream in class me.drton.jmavlib.mavlink.MAVLinkStream cannot be applied to given types;
required: me.drton.jmavlib.mavlink.MAVLinkSchema,java.nio.channels.ByteChannel
found: me.drton.jmavlib.mavlink.MAVLinkSchema
reason: actual and formal argument lists differ in length
Error:(51, 42) java: 'void' type not allowed here
Error:(66, 29) java: method read in class me.drton.jmavlib.mavlink.MAVLinkStream cannot be applied to given types;
required: no arguments
found: java.nio.ByteBuffer
reason: actual and formal argument lists differ in length
F:\jMAVSim\la4j\src\main\java\org\la4j\matrix\MatrixFactory.java
Information:java: Some input files use unchecked or unsafe operations.
Information:java: Recompile with -Xlint:unchecked for details.

I tried "fixing" what the IDE didn't like by changing, adding (existing objects), or removing arguments and in one case changing an import statement ("import org.la4j.matrix.Matrix;" to "import org.la4j.Matrix;"). That allowed the project to build, but I can't find the jar file anywhere. First of all, were the changes I made appropriate? If not, what should have been done? If I'm ok through the build step, what do I need to do to generate a jar file?

Sedro
Dec 31, 2008
Did you git clone --recurse-submodules ? They are using submodules for dependency management. It looks like you might be using the wrong commit for those dependencies.

There's an ant script to build a jar (you can call it from the `Build` menu in IDEA).

hooah
Feb 6, 2006
WTF?

Sedro posted:

Did you git clone --recurse-submodules ?

I did not, since I didn't know about that command. Did that and ant ran fine. However, I can't run it; when I try from the command line I get the message "Could not find or load main class".

hooah fucked around with this message at 00:41 on Mar 9, 2015

Sedro
Dec 31, 2008
Who knows... they offer no instructions about building or running the software. You could try running it through the IDE. If that works, I think IDEA can make you a JAR somehow.

Data Graham
Dec 28, 2009

📈📊🍪😋



Hey guys, I need wiser and more patient heads than my own to help me with a Java/JSP problem that keeps cropping up.

I have openjdk8 installed (FreeBSD). I'm running tomcat8 like this, which is the default configuration installed by the tomcat package:

/usr/local/bin/jsvc -java-home /usr/local/openjdk8 -server -user www -pidfile /var/run/tomcat8.pid -wait 30 -outfile /usr/local/apache-tomcat-8.0/logs/catalina.out -errfile &1 -classpath /usr/local/apache-tomcat-8.0/bin/bootstrap.jar:/usr/local/share/java/classes/commons-daemon.jar:/usr/local/apache-tomcat-8.0/bin/tomcat-juli.jar -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.util.logging.config.file=/usr/local/apache-tomcat-8.0/conf/logging.properties -Djava.endorsed.dirs=/usr/local/apache-tomcat-8.0/endorsed -Dcatalina.home=/usr/local/apache-tomcat-8.0 -Dcatalina.base=/usr/local/apache-tomcat-8.0 -Djava.io.tmpdir=/usr/local/apache-tomcat-8.0/temp org.apache.catalina.startup.Bootstrap

I have a JSP page with this in it:

code:
<%@ page import="java.awt.*"%>
<%@ page import="javax.swing.*"%>
But periodically, seemingly after I reboot or tinker with the install or anything, I get this:

code:
javax.el.ELException: The package [java.awt] could not be found
(Same thing with javax.swing if I comment the awt line out.)

I hosed with this a little while ago and swapped out libraries and things and it mysteriously started working, but then last night it broke again (I suspect after I rebooted, implying that something changed in the tomcat startup parameters).

Thing is, I don't have any idea where to look to see why it's not finding these libraries. I poke through /usr/local/openjdk8 and nothing looks familiar. People discussing problems like this seem to usually point to JAVA_HOME not being set properly, but I've got it set in my (root) environment, and -java-home is being specified in the tomcat startup options.

Can someone please help me understand what's going on here? Thanks.

Data Graham
Dec 28, 2009

📈📊🍪😋



Here's a more focused demo of the above:

code:
<%@ page import="java.awt.*"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="blah" value="foo" />
blah: <c:out value="${blah}" />
If I remove the java.awt line, it works fine, and prints out "blah: foo". But with that line in there, I get the error, seemingly triggered on the <c:out> line.

code:
org.apache.jasper.JasperException: An exception occurred processing JSP page /test2.jsp at line 6

3: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
4: 
5: <c:set var="blah" value="foo" />
6: blah: <c:out value="${blah}" />


Stacktrace:
	org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:567)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:469)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

javax.el.ELException: The package [java.awt] could not be found
	javax.el.ImportHandler.importPackage(ImportHandler.java:135)
	org.apache.jasper.runtime.PageContextImpl.getELContext(PageContextImpl.java:948)
	org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:933)
	org.apache.jsp.test2_jsp._jspx_meth_c_005fout_005f0(test2_jsp.java:164)
	org.apache.jsp.test2_jsp._jspService(test2_jsp.java:112)
	org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
	org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:431)
	org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
	org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note that this also works fine:

code:
<%@ page language="java" import="java.util.*,java.io.*,java.sql.*,javax.sql.*,javax.naming.*,java.security.*,java.math.*" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="blah" value="foo" />
blah: <c:out value="${blah}" />
But not this:

code:
<%@ page language="java" import="java.util.*,java.io.*,java.sql.*,javax.sql.*,javax.naming.*,java.security.*,java.math.*,java.awt.*" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="blah" value="foo" />
blah: <c:out value="${blah}" />
So it seems like specifically java.awt and java.swing that break <c:out>, or something? WTF.

1337JiveTurkey
Feb 17, 2005

Are you using an openjdk version designed only to be run on a headless server? There's specifically headless distributions that IIRC don't even have the AWT and Swing packages in them. Normally Java will run with the libraries but throw an exception if it tries to setVisible() in headless mode. That still allows for rendering to images and printing but if you don't need that, you don't need the libraries.

Data Graham
Dec 28, 2009

📈📊🍪😋



Yeah, I do need the graphics libs; I'm directly using stuff like ImageIcon.

I'll check to see if there's a headless version that I installed by mistake or something.


E: Not that I can tell. There's a /usr/local/openjdk8/jre/lib/amd64/libawt_headless.so in the install; I'm not sure what that tells me though.

Data Graham
Dec 28, 2009

📈📊🍪😋



There are installable ports for openjdk8 (which includes a jre), and openjdk8-jre; I only had the former installed, now I'm trying the latter.

Both have (in different places):

code:
# ls -l /usr/local/openjdk8/jre/lib/amd64/
total 3078
-r-xr-xr-x  1 root  wheel    9268 Mar  6 03:00 jexec
drwxr-xr-x  2 root  wheel       3 Mar  9 09:46 jli
-r-xr-xr-x  1 root  wheel   16146 Mar  6 03:00 jspawnhelper
-r--r--r--  1 root  wheel    1624 Mar  6 03:00 jvm.cfg
-r--r--r--  1 root  wheel   11806 Mar  6 03:00 libattach.so
-r--r--r--  1 root  wheel  682957 Mar  6 03:00 libawt.so
-r--r--r--  1 root  wheel   34205 Mar  6 03:00 libawt_headless.so
-r--r--r--  1 root  wheel  424170 Mar  6 03:00 libawt_xawt.so
-r--r--r--  1 root  wheel   22230 Mar  6 03:00 libdt_socket.so
-r--r--r--  1 root  wheel  419732 Mar  6 03:00 libfontmanager.so
-r--r--r--  1 root  wheel  186885 Mar  6 03:00 libhprof.so
-r--r--r--  1 root  wheel  100769 Mar  6 03:00 libinstrument.so
-r--r--r--  1 root  wheel   44489 Mar  6 03:00 libj2gss.so
-r--r--r--  1 root  wheel   17328 Mar  6 03:00 libj2pcsc.so
-r--r--r--  1 root  wheel   76005 Mar  6 03:00 libj2pkcs11.so
-r--r--r--  1 root  wheel    7367 Mar  6 03:00 libjaas_unix.so
-r--r--r--  1 root  wheel  204359 Mar  6 03:00 libjava.so
-r--r--r--  1 root  wheel   34293 Mar  6 03:00 libjava_crw_demo.so
-r--r--r--  1 root  wheel    6510 Mar  6 03:00 libjawt.so
-r--r--r--  1 root  wheel  257923 Mar  6 03:00 libjdwp.so
-r--r--r--  1 root  wheel  201642 Mar  6 03:00 libjpeg.so
-r--r--r--  1 root  wheel   10865 Mar  6 03:00 libjsdt.so
-r--r--r--  1 root  wheel   10193 Mar  6 03:00 libjsig.so
-r--r--r--  1 root  wheel    6767 Mar  6 03:00 libjsound.so
-r--r--r--  1 root  wheel   80437 Mar  6 03:00 libjsoundalsa.so
-r--r--r--  1 root  wheel  364056 Mar  6 03:00 liblcms.so
-r--r--r--  1 root  wheel   41895 Mar  6 03:00 libmanagement.so
-r--r--r--  1 root  wheel  907028 Mar  6 03:00 libmlib_image.so
-r--r--r--  1 root  wheel  102505 Mar  6 03:00 libnet.so
-r--r--r--  1 root  wheel   81812 Mar  6 03:00 libnio.so
-r--r--r--  1 root  wheel   14041 Mar  6 03:00 libnpt.so
-r--r--r--  1 root  wheel   52974 Mar  6 03:00 libsaproc.so
-r--r--r--  1 root  wheel   28228 Mar  6 03:00 libsctp.so
-r--r--r--  1 root  wheel  318870 Mar  6 03:00 libsplashscreen.so
-r--r--r--  1 root  wheel  208532 Mar  6 03:00 libsunec.so
-r--r--r--  1 root  wheel  125226 Mar  6 03:00 libunpack.so
-r--r--r--  1 root  wheel   66959 Mar  6 03:00 libverify.so
-r--r--r--  1 root  wheel   40960 Mar  6 03:00 libzip.so
drwxr-xr-x  2 root  wheel       5 Mar  9 09:46 server
And tomcat is running with -java-home set to /usr/local/openjdk8-jre. But same behavior as before.

Tried running with -Djava.awt.headless=true too.


E: And just to be clear: it only seems to be <c:> that fucks everything up. If I change this one particular <c:set> near the top of the file:

<c:set var="basepath_local" value="${sessionScope.basepath}" scope="page" />

to

<c:set var="basepath_local" scope="page" value="/usr/local/apache-tomcat-8.0/webapps/ROOT" />

Then it all works fine, including the ImageIcon calls and stuff that uses awt/swing.

And it's not because of sessionScope; same thing happens if I use a variable from a different scope.

Data Graham fucked around with this message at 20:03 on Mar 9, 2015

Data Graham
Dec 28, 2009

📈📊🍪😋



Hokay. So what it seems to be doing is trying—and failing, for some unknown reason—to set a variable, but then afterwards whatever was causing the exception recovers its bearings and everything is fine.

I had a <c:catch> around some input validation stuff a little further down the initial page I was working on, which was swallowing the java.awt exception and then allowing the rest of the script to proceed normally, including all the stuff using AWT. That's what was making debugging this thing so confusing.

So here's what works, 100% of the time so far:

code:
<c:catch var="catchException">
    <c:set var="basepath_local" value="${sessionScope.basepath}" scope="page" />
</c:catch>
<c:if test="${catchException != null}">
    <c:set var="basepath_local" value="${sessionScope.basepath}" scope="page" />
</c:if>
:catstare:

1337JiveTurkey
Feb 17, 2005

Unfortunately I don't know much about JSP, just classloading issues so take this with a grain of salt. The stack trace points to it happening during the creation of the ELContext which apparently happens during the loading of the JSTL. Apparently the following bug fix started loading every package from the import:

https://bz.apache.org/bugzilla/show_bug.cgi?id=57142

So I'm guessing it's not finding the package in the ELContext for Expression Language parsing and gives the error. Everything else doesn't care I guess if they're not using the EL. Maybe factor out any AWT/Swing code so that it's not in a servlet page?

Data Graham
Dec 28, 2009

📈📊🍪😋



It's not a servlet, just a plain old JSP. I've never done anything with servlets, and am pretty unclear on what goes into making one. I've been trying to hackishly try tomcat6 to check if that fix is to blame but can't get it running properly.

The page in question is an image uploader. I'm setting various session variables and then calling this JSP via AJAX with a form post. Theoretically the session variables should all be available, and they are, but apparently when the JSP is first being initiated the first JSTL <c:set> tag that refers to an external variable triggers this weird "can't find java.awt" thing. Like, I can <c:set var="foo" value="bar" /> but not <c:set var="foo" value="${bar}" />.

So this also works:

code:
<c:catch var="catchException">
    <c:set var="foo" value="${bar}" scope="page" />
</c:catch>

<c:set var="basepath_local" value="${sessionScope.basepath}" scope="page" />
Which I might as well use just as a band-aid at the top of all my pages. I just hate not understanding things.

Data Graham fucked around with this message at 23:09 on Mar 9, 2015

1337JiveTurkey
Feb 17, 2005

That ${foo} is the expression language that I was mentioning so anything that uses it initializes an ELContext which is what's trying to load java.awt to my knowledge. My recommendation is to put that code into a plain old java class that you reference from the page rather than including the image manipulation logic there.

Data Graham
Dec 28, 2009

📈📊🍪😋



Aha, I see. Thanks, I'll try that.

Data Graham
Dec 28, 2009

📈📊🍪😋



I apologize in advance for this. I wouldn't want my worst enemy to have to stare down the barrel of a keytool question.


Trying to import a newly generated code signing cert from GoDaddy. The file is in .spc format, which I take to mean PKCS#7.

I'm following these instructions, which people seem to be saying are good: https://support.godaddy.com/help/article/4780/java-code-signing-generating-a-csr

But maybe they're written for a different version of java or something, because in steps 3 and 4, the -storepass option seems to require an argument in my version, but they seem to think you can just toss it in there without one. (If I leave it out, it prompts me for the password, which I prefer anyway.)

But I keep getting this:

code:
# keytool -importcert -trustcacerts -keystore keystore.jks -alias codesigncert -file e6c287786fc96d5d.spc 
keytool error: java.lang.Exception: Input not an X.509 certificate
Which is weird, because I can do this:

code:
# keytool -printcert -file e6c287786fc96d5d.spc 
Certificate[1]:
... 
And it lists pages of seemingly accurate information.

I'm not sure what to do from here. Anyone wrestled with this one lately?

Volguus
Mar 3, 2009
There's nowhere in those instructions any mention of a spc file. Get the .cer file and execute (as per the instructions):
code:
keytool -import -trustcacerts -keystore codesignstore -storepass -alias codesigncert -file [b]mycert.cer[/b]
I've done this recently, and I got from the authority (wasn't GoDaddy, but it should be the same crap) a .cer file that I was able to use to sign my jar . The instructions posted there look correct. Just follow them.

(no idea where the .cer file comes from since the IT guy did the actual transaction with CC payment and stuff, but ... if he could manage it, so can you).

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Data Graham posted:

I apologize in advance for this. I wouldn't want my worst enemy to have to stare down the barrel of a keytool question.


Trying to import a newly generated code signing cert from GoDaddy. The file is in .spc format, which I take to mean PKCS#7.

I'm following these instructions, which people seem to be saying are good: https://support.godaddy.com/help/article/4780/java-code-signing-generating-a-csr

But maybe they're written for a different version of java or something, because in steps 3 and 4, the -storepass option seems to require an argument in my version, but they seem to think you can just toss it in there without one. (If I leave it out, it prompts me for the password, which I prefer anyway.)

But I keep getting this:

code:
# keytool -importcert -trustcacerts -keystore keystore.jks -alias codesigncert -file e6c287786fc96d5d.spc 
keytool error: java.lang.Exception: Input not an X.509 certificate
Which is weird, because I can do this:

code:
# keytool -printcert -file e6c287786fc96d5d.spc 
Certificate[1]:
... 
And it lists pages of seemingly accurate information.

I'm not sure what to do from here. Anyone wrestled with this one lately?

If you can open that .spc file in a text editor and it's actually readable then you are using a PEM encoded file and keytool only likes DER/CER encoded files. I know you used it to print the contents of the .spc file but I think that's confusingly the only use case where it will accept a PEM file.

Data Graham
Dec 28, 2009

📈📊🍪😋



Nah, it's in the right format; apparently GoDaddy always uses .spc for its files, which are in binary PKCS#7. Which you can clearly infer from their download page:



:hurr:

Turns out I was using the wrong alias name, as I should have been able to figure out from the helpful exception message, I guess.

(Also it seems openjdk has its own ideas about what kinds of options keytool should support, so you use -importcert instead of -import, but -import still works as an alias to -importcert, even though it isn't listed in the options)

Data Graham fucked around with this message at 02:48 on Mar 11, 2015

ROFLburger
Jan 12, 2006

Can someone help me understand possible reasons that this method would return an uppercase'd sha256? It seems to me like the method would be returning a completely different and unique has than the one that was created. Does sha256 only produce numeric/alpha lowercase output or something?
code:
    private String tosha256(String str){
        StringBuilder sb = new StringBuilder();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(str.toLowerCase().getBytes("ASCII"));
            byte[] hash = md.digest();

            for(Byte b : hash){
                sb.append(b);
            }

        return sb.toString().toUpperCase();
    }

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Sample output from that method:
5459-4125-710512670-268175-15-16-17-501490-5011710454-105-5-1260101-9692-113-771994
I suspect whoever wrote that wanted hex output but never tested it. I don't think that method is useful at all in its current form.

FAT32 SHAMER
Aug 16, 2012



I guess I accidentally hit preview instead of post, so here it goes again.

I'm kind of rusty on my Java, and in my software engineering class they're teaching us the ins and outs of Java instead of the the finer practices of software engineering or whatever they're supposed to be teaching us. I'm supposed to take this .txt file:
code:
John King 39 99 29

Joe Sample 88 90
Joev Barker 79 ** 88 +++ 88 
Leslie Muller 77 88 99 100
find the average for each student, and ignore any noise-data such as the white space on line two and the ** and +++ on line 4, then put them into a new .txt file that will look like this:
code:
John King 56
Joe Sample 89 
Joev Barker 85 
Leslie Muller 91
Additional insight on it

quote:

-Each line may contain various numbers of integer score numbers (line one above contains three integer scores, whereas line three only contains two integers)
- Empty lines should be skipped (line two above)
- Your code should be able to jump over corrupted data in each line (like “**” and“+++” on line four above and still correctly generate the corresponding average score of 85 as shown at the output file below)
-The separator between each data item on each line can be one or more spaces

This is what I have so far, but I have a nagging suspicion that I'm going about it completely wrong.
Java code:
package AverageScoreCalculator;

import java.util.*;
import java.io.*;


public class AverageScoreCalculator
{    
    public static void main( String[] args ) throws IOException
    {
        Scanner input = new Scanner( new FileReader( "scores.txt" ) );
        PrintWriter output = new PrintWriter("AverageScores.txt");
        
        int sum = 0;
        
        for( int i = 0; i < 5; i++ )
        {
            String firstName = input.next();
            output.println( firstName );
            String lastName = input.next();
            output.println( lastName );
            int score = input.nextInt();
            sum += score;
            float averageScore = sum / 4;
            output.println( averageScore );
        }
        
        output.close();
    }
    public void writeAverageScore()
    {
        
    }
}

How do I go about parsing out the noise-data? Is there a better way to loop through each line to pull the firstname/lastname/scores?

edit: you can ignore the empty writeAverageScore method, I forgot to delete it after deciding using multiple methods would be slightly more annoying

FAT32 SHAMER fucked around with this message at 08:11 on Mar 13, 2015

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

I'd say that you should read through the file line by line rather than token by token. Then you can further tokenize that line (String.split(' ') will be convenient here) and go through each token on that line, knowing that the first is the first name, the second is the last name, and that each further token should be convertible to an integer. If it isn't, you know it's garbage and can skip.

FAT32 SHAMER
Aug 16, 2012



carry on then posted:

I'd say that you should read through the file line by line rather than token by token. Then you can further tokenize that line (String.split(' ') will be convenient here) and go through each token on that line, knowing that the first is the first name, the second is the last name, and that each further token should be convertible to an integer. If it isn't, you know it's garbage and can skip.

Hmm, so I tried this:

Java code:
     public static void main( String[] args ) throws IOException
    {
        Scanner input = new Scanner( new FileReader( "scores.txt" ) );
        PrintWriter output = new PrintWriter("AverageScores.txt");
        
        int sum = 0;
        
        for( int i = 0; i < 6; i++ )
        {
            String delims = "[ .,?!*+/ ]+";
            String[] tokens = input.split(delims);
            String firstName = tokens[0];
            String lastName = tokens[1];
            
            int scores = input.nextInt();
            sum += scores;
            float average = sum / 5;
            
            output.println( firstName );
            output.println( lastName );
            output.println( average );
        }
        
        input.close();
        output.close();
    }
But the error message says that the array is only ever written to, not read from. Can you not tokenize scanner or something?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Yeah, you have to split a string. So get the whole line out of the input, and split that (you only need to split on a space.) Then ignore the scanner for working on that line, instead use Integer.valueOf or similar to make ints out of the number for each score. Think of how you could identify both blank lines, and garbage data (for the latter case, do you want to check ahead, or check for failure?)

carry on then fucked around with this message at 21:20 on Mar 13, 2015

FAT32 SHAMER
Aug 16, 2012



carry on then posted:

Yeah, you have to split a string. So get the whole line out of the input, and split that (you only need to split on a space.) Then ignore the scanner for working on that line, instead use Integer.valueOf or similar to make ints out of the number for each score. Think of how you could identify both blank lines, and garbage data (for the latter case, do you want to check ahead, or check for failure?)

Okay I'm starting to get it, plus it didn't help that it didn't like \s instead of " " :shobon:

Java code:
public static void main( String[] args ) throws IOException
    {
        Scanner input = new Scanner( new File( "scores.txt" ) );
        PrintWriter output = new PrintWriter( "AverageScores.txt" );
        
        int sum = 0;
        
        for( int i = 0; i < 5; i++ )
        {
            String line = input.nextLine();
            String cleanedLine = line.replaceAll("[^a-zA-Z0-9]"," ");
            String [] tokens = cleanedLine.split(" ");
            String firstName = tokens[0];
            String lastName = tokens[1]; //Line 22
            String test1 = tokens[2];
            String test2 = tokens[3];
            String test3 = tokens[4];

            int parseScores =  Integer.valueOf( test1 ) + Integer.valueOf( test2 ) + Integer.valueOf( test3 );
            
            float average = parseScores / 3;
         
            
            output.println( firstName );
            output.println( lastName );
            output.println( average );
        }
        
        input.close();
        output.close();
    }
It's still failing on line 22 for some reason and it's only giving me a cryptic Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at AverageScoreCalculator.AverageScoreCalculator.main(AverageScoreCalculator.java:22) Java Result: 1.

I did a test run by printing every line to make sure it got cleaned up and it did, which is good, but it doesn't seem to like me assigning certain tokens to variables.

edit: the error means the code tried to access element index 1 of an array that has less than 2 elements. Not sure how that's possible since every line should have fName/lName/t1/t2/t3 5 elements [0]-[4]

FAT32 SHAMER fucked around with this message at 22:13 on Mar 13, 2015

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Think about which line in your input file might only have one token. That should tell you what you need to check for to avoid one of the instances of malformed data the assignment mentions.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Are you using an IDE? Saddle up that debugger, and let's mosey

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Tusen Takk posted:

edit: the error means the code tried to access element index 1 of an array that has less than 2 elements. Not sure how that's possible since every line should have fName/lName/t1/t2/t3 5 elements [0]-[4]

This assumption isn't quite right. Take another look at the extra info you posted; it's crashing because of one of those issues. And seconding the debugger, using it should show you a bit more about how things are actually happening.

FAT32 SHAMER
Aug 16, 2012



I totally forgot that the last line of the input file had four scores associated with the student :shobon:

Java code:
public static void main( String[] args ) throws IOException
    {
        Scanner input = new Scanner( new File( "scores.txt" ) );
        PrintWriter output = new PrintWriter( "AverageScores.txt" );
                
        for( int i = 0; i < 6; i++ )
        {
            String line = input.nextLine();
            if ( line.isEmpty() )
            {
                line = input.nextLine();
            }
            String cleanedLine = line.replaceAll("[^a-zA-Z0-9]"," ");
            String [] tokens = cleanedLine.split(" ");
            String firstName = tokens[0];
            String lastName = tokens[1];
            
            for( int j = 2; j < tokens.length; j++ )
            {
                String score = tokens[j];
                int parsedScore = Integer.valueOf( score );
                int sum = 0;
                sum += parsedScore;
                float average = sum / 4;
		output.println( firstName + " " + lastName + " " + average );
            }
        }
        
        input.close();
        output.close();
    }
I'm still getting an error but it's looking much more like how it should, and yeah I'll try the debugger and see what happens.

FAT32 SHAMER fucked around with this message at 22:49 on Mar 13, 2015

Volguus
Mar 3, 2009
If you're dead-set on that Scanner class, why not use while(scanner.hasNextLine()) as your loop?

FAT32 SHAMER
Aug 16, 2012



Volguus posted:

If you're dead-set on that Scanner class, why not use while(scanner.hasNextLine()) as your loop?

Im supposed to use the scanner class as per the assignment, but I didn't know if that while loop would work since line 2 of the .txt file is a blank line

Volguus
Mar 3, 2009

Tusen Takk posted:

Im supposed to use the scanner class as per the assignment, but I didn't know if that while loop would work since line 2 of the .txt file is a blank line

I guess there's only one way to find out.
And if you absolutely must use the scanner, please use whatever expletive you want on the teacher. He/she deserves it. And after you're done with the school, forget that it even exists, please.

Adbot
ADBOT LOVES YOU

FAT32 SHAMER
Aug 16, 2012



Volguus posted:

I guess there's only one way to find out.
And if you absolutely must use the scanner, please use whatever expletive you want on the teacher. He/she deserves it. And after you're done with the school, forget that it even exists, please.

I've been told by many users on this site that based on the assignments I come in the CoC looking for help, it's best to just forget everything I learn from the classes and try to absorb as much good practices as I can in a real job.

Luckily, I have one lined up starting in late April/early May, so that will definitely help me grow :)

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