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
Titan Coeus
Jul 30, 2007

check out my horn

Joda posted:

Output:
code:
1 recursions: -3.9298
2 recursions: 0.12068800666666757
3 recursions: -1.2105183783510216
4 recursions: -0.9761404770345857
5 recursions: -1.0018168365436917
6 recursions: -0.9998989681026615
7 recursions: -1.0069810853034464
8 recursions: -0.9624220627974793
9 recursions: 0.01762731720225519
10 recursions: -4.112208875974112
Oh. So, as far as I can tell now, I'm breaking the limitations of the data types if I go over k = 8 for x = pi. Is that correct? If so, that's a bloody load off my mind. I was going through my discrete maths notes and everything worried I might've completely misunderstood something.

Thanks a lot for that. That's a mistake I'm not going to make again.

EDIT: Wait, shouldn't it return NaN if I've broken the limit of a data type?

NaN is only for floating point arithmetic (and you shouldn't depend on getting NaN regardless).

See the output of the following for some insight into your issue:

code:
System.out.println(2147483647 + 1);

Adbot
ADBOT LOVES YOU

nbzl
Apr 5, 2002

Don't worry about the horse being blind, just load the wagon.
I've also got a recursion based question:

code:
    public boolean find(String t) {
        if (text.length() <= 1) {
            return false;
        } else if (text.equals(t)) {
            System.out.println("Found it!")
            return true;
        } else if (text.length() > 1) {
            text = text.substring(0, (text.length() - 1));
            System.out.println(text + " " + t);
            find(t);
        } 
            return false;      
    }
This method seems to always return false even though I get the 'Found it!' to display. Is there something I'm missing here? I was under the impression that it would end the method and return the true value.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

nbzl posted:

I've also got a recursion based question:

code:
    public boolean find(String t) {
        if (text.length() <= 1) {
            return false;
        } else if (text.equals(t)) {
            System.out.println("Found it!")
            return true;
        } else if (text.length() > 1) {
            text = text.substring(0, (text.length() - 1));
            System.out.println(text + " " + t);
            find(t);
        } 
            return false;      
    }
This method seems to always return false even though I get the 'Found it!' to display. Is there something I'm missing here? I was under the impression that it would end the method and return the true value.

Think about what you'd have to do with the result of find() to punt the answer up the call stack.

nbzl
Apr 5, 2002

Don't worry about the horse being blind, just load the wagon.

carry on then posted:

Think about what you'd have to do with the result of find() to punt the answer up the call stack.

Changing
code:
else if (text.length() > 1) {
            text = text.substring(0, (text.length() - 1));
            find(t);
        }
to
code:
else if (text.length() > 1) {
            text = text.substring(0, (text.length() - 1));
            return find(t);
        }
achieved the desired result. Thank you for the help.

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
Will JavaDoc generation only work if the program has no errors? This seems to be the case but I just figured I'd double check.

Max Facetime
Apr 18, 2009

Good Will Punting posted:

Will JavaDoc generation only work if the program has no errors? This seems to be the case but I just figured I'd double check.

I'd imagine it depends on the tool, but I doubt it goes beyond the syntactical analysis needed to figure out what classes, fields, methods etc. there are.

Should be easy to test with some nonsensical code like:

Java code:
public class Test {
  public static Test method() {
    return 0; // Intentional wrong type of value
  }
}

fadderman
Feb 3, 2008
dyslectic lurker
i am having troubles creating a build.xml file that works with Travis CI. I had Eclipse export a ant build file for me but this one does not have a target for test which i am getting a error for

here is my build file i have genarated http://pastebin.com/XLnYf2H6
I have almost never made build files so i don't know proper way to add mine test folder as target for mine junit test, do you guys have any tips on how to do it

geeves
Sep 16, 2004

Struts 2 question (possibly). And it's difficult to explain so I hope this comes across simple to follow.

I have a user-created dynamic form that's built with loading components via ajax (for cardinality, nested form fields, etc.).

All of the fields dynamically added have a name of formfield[N]. N being the row index.

Due to the dynamic ajax loading, for each added field, incrementing is not sequential, but skips by 10 (for more complicated reasons, it cannot be sequential as technically we're loading 2 or 3 fields not just one).

When the form is submitted, it thinks the formfield List size is 100, instead of just 10. That's been fine, until now.

When the form fails validation, (the values are saved no matter what) the formfield List is reloaded in the Action. The Action would clear out and null the formfield List and get a fresh set of the List from the DB.

What is happening now, is that the formfield List still thinks it has 100 members and outputs 100 fields instead of just 10 fields (though logs and debugs say there is only 10 members).

Following the debugger, 10 are loaded and all the data matches up, but instead 100 fields are now displayed once formfield gets to the JSP. It seems that something in Java or Struts is keeping the submitted formfield List in cache / memory / something instead of using the cleared, null'd & fresh formfield List.

I've been stuck on this for most of the day, and really having a hard time asking the right question.

The HTML would look something like this (these have been dynamically added):

code:
<input type="text" name="formfield[0]"/>
<input type="text" name="formfield[10]"/>
<input type="text" name="formfield[20]"/>
<input type="text" name="formfield[30]"/>
In the action

code:
for (Formfield f : formfield) {
    // do validation
    // save value to db
}

formfield = null;

formfield = hibernateManager.getFormfields(formId);
log.info("form field size: " + formfield.size()); // outputs 4 in logs and debugger

And what then gets outputted when needing validation - 30 instead of just 4

code:
<input type="text" name="formfield[0]"/>
...
<input type="text" name="formfield[29]"/>
I've fixed this. There was an <s:action /> that was missing ignoreContextParams="true" so the request scope of formfield from that Action was overwriting what came out of the primary Action.

geeves fucked around with this message at 17:55 on Oct 3, 2012

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Anybody have any idea how to load classes from a doubly-nested JAR?
My situation: Eclipse can create a JAR containing an app, its library JARs, and the JarRsrcLoader main class to run it all.
This works fine as long as all the libraries you use are platform-neutral. SWT is not. It's simple to modify the normal Eclipse solution to choose which JAR to load at runtime, but this has an issue: size bloat. Supporting Windows + Linux costs ~6MB. Adding OS X adds another ~4MB.

My incomplete attempt at a solution to this is currently:
  • Unpack all the SWT libs I want to support
  • Repack them as individual uncompressed JARs
  • Pack all of the libs into one uncompressed zip
  • Compress this zip with XZ
The resulting .zip.xz is 2.8MB and has the files needed to support Windows, OS X, and Linux. Much better.
But I don't know where to go from here. Somehow I need to give a classloader access to the nested JAR it needs to get at the SWT lib for my platform, which means it needs to decompress the zip, open the zip, then search the right JAR for the classes/native libraries. I'm lost.

omeg
Sep 3, 2012

Probably a stupid newbie question that gets asked a lot, but: why Runtime.getRuntime().exec("console_program.exe") doesn't show the console? The process hangs on console IO, but that's probably because I don't handle its IO on the Java side. Why does exec() change how my program works? I want the console program to display some diagnostic output (I wrote it) and don't want to mess with its IO streams from Java.

Context: the Java code is in a custom extension for a certain application that uses Eclipse Rich Client as a base for GUI.

Max Facetime
Apr 18, 2009

This may not be directly helpful, but I took a look at how SWT loads native libraries from inside a jar-file. It looks like if the DLL doesn't already exist on the filesystem, it is extracted from the jar-file to an actual file before it is loaded with System.loadLibrary().

This makes sense since the native library loading happens in the DLL path world by Windows rather than in the analogous classpath world by the JVM.

Max Facetime
Apr 18, 2009

omeg posted:

Probably a stupid newbie question that gets asked a lot, but: why Runtime.getRuntime().exec("console_program.exe") doesn't show the console? The process hangs on console IO, but that's probably because I don't handle its IO on the Java side. Why does exec() change how my program works? I want the console program to display some diagnostic output (I wrote it) and don't want to mess with its IO streams from Java.

Context: the Java code is in a custom extension for a certain application that uses Eclipse Rich Client as a base for GUI.

Is this a difference between double-clicking the console_program.exe in Windows versus calling .exec()?

This might be case of the Windows desktop environment being helpful when it sees that console_program.exe hasn't created a window for itself but it is using console input. Maybe
Java code:
Desktop.getDesktop().open(Paths.get("console_program.exe").toFile());
is more like what you want.

omeg
Sep 3, 2012

Win8 Hetro Experie posted:

Is this a difference between double-clicking the console_program.exe in Windows versus calling .exec()?

Pretty much.

Java code:
Desktop.getDesktop().open(Paths.get("console_program.exe").toFile());
This works fine, thanks. It would be nice to get exit code or somehow synchronize with the child process though.

E: Also that method doesn't allow to painlessly pass parameters to the child program.

omeg fucked around with this message at 14:12 on Oct 3, 2012

Max Facetime
Apr 18, 2009

omeg posted:

This works fine, thanks. It would be nice to get exit code or somehow synchronize with the child process though.

E: Also that method doesn't allow to painlessly pass parameters to the child program.

In that case using Runtime to create a Process to get its return value sounds more straightforward.

A similar situation might arise if you had a command-line script whose output you wanted saved to a file, but one part of it calls console_program.exe and you wanted its output to go to a separate window and only use its return value.

Maybe wrapping the command in a CMD-script and doing something like this
code:
START "title" /WAIT console_program.exe arguments
is the ticket, but in any case this sounds more like a question about process handling in Windows than a Java question.

Hoops
Aug 19, 2005


A Black Mark For Retarded Posting
Can someone help me with some very, very basic introductory problems with installing Java? I don't know a thing about computers. (Originally posted this in the Javascript thread, for example). I've tried 4 different tutorials but they're all getting on my nerves because they just start talking about things I've never even heard of. It's maddening.

So: I have downloaded the Java Development Kit from the Sun website. I clicked "next" and all that through the installation process, without changing any directories at all.

1) I'm being told to download the Java SE API Documentation, which apparently is this. What do I actually download? That's a list of a hundred things that mean absolutely loving nothing. I'm losing my patience at these guides because they go into minute detail about stuff that someone would have to understand to even be reading the website, but the vaguest instructions on the actual stuff that computer-laymans don't know.

2) Once I have this API documentation, it says to unzip it into my Java home directory. I assume my Java home directory is the directory that I just installed that JDK in, which was C:\Program Files\Java

Once I have that, there should be a folder named "docs".

That's where I'm up to.

Tots
Sep 3, 2007

:frogout:

Hoops posted:

Can someone help me with some very, very basic introductory problems with installing Java? I don't know a thing about computers. (Originally posted this in the Javascript thread, for example). I've tried 4 different tutorials but they're all getting on my nerves because they just start talking about things I've never even heard of. It's maddening.

So: I have downloaded the Java Development Kit from the Sun website. I clicked "next" and all that through the installation process, without changing any directories at all.

1) I'm being told to download the Java SE API Documentation, which apparently is this. What do I actually download? That's a list of a hundred things that mean absolutely loving nothing. I'm losing my patience at these guides because they go into minute detail about stuff that someone would have to understand to even be reading the website, but the vaguest instructions on the actual stuff that computer-laymans don't know.

2) Once I have this API documentation, it says to unzip it into my Java home directory. I assume my Java home directory is the directory that I just installed that JDK in, which was C:\Program Files\Java

Once I have that, there should be a folder named "docs".

That's where I'm up to.

Gotta take a step back quick before we give you more instructions. Installing Java and installing JDK are two very different things. What do you need to use Java for? Is it for development or is it just to run applications built using java?

baquerd
Jul 2, 2007

by FactsAreUseless

Hoops posted:

So: I have downloaded the Java Development Kit from the Sun website. I clicked "next" and all that through the installation process, without changing any directories at all.

Then you now have Java, you're set.

Tots posted:

Installing Java and installing JDK are two very different things.

Not really, the JDK is "Java" wrapped with dev tools.

Max Facetime
Apr 18, 2009

I really want to suggest using Eclipse but I'm almost certain that would do more harm than good :shepface:

Hoops
Aug 19, 2005


A Black Mark For Retarded Posting

Tots posted:

Gotta take a step back quick before we give you more instructions. Installing Java and installing JDK are two very different things. What do you need to use Java for? Is it for development or is it just to run applications built using java?
It's for a course I'm taking. I don't know exactly what we'll be doing with it yet but it will be generally, simple computational optimization (Simplex method, some interior point methods, etc).

I thought the installation had gone fine, but I'm trying to do the very initial stuff with java (a script that makes it say "Hello World", seems like that's a common starting point) and the command console says it doesn't know what "javac" is.

I was in the same directory as the script (written in notepad, saved as a text file) but it was having none of it.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Java is painful in that regard because it assumes you know some very basic things like what your PATH is and how to manipulate it. I've always felt it was a shortcomming of the installer to not add the java bin directory to my PATH.

Do this first, and you'll be able to execute the javac command how you want.
http://java.com/en/download/help/path.xml

IMlemon
Dec 29, 2008
I'm somewhat lost in regards to Spring transaction management, most of the documentation I looked at seems really complex and overwhelming, maybe someone here can dumb it down for me :downs:

Java code:
@Transactional
public void doWork() {
try{
			doDbRelatedWork()
			logSuccessToDb()

		} catch(Exception e) {

			logErrorToDb(e)
		}
}
So, I want to log error cause into db if something goes wrong. The problem is, we're still in the scope of transaction when exception occurs so my logging gets rolled back. Any ideas how I can achieve this?

edit: That makes perfect sense and I have no idea how I could miss that solution.

IMlemon fucked around with this message at 15:38 on Oct 5, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Catch the exception further up?

Hot Yellow KoolAid
Aug 17, 2012
Can anybody here who programs Java on linux help me? I have a new 12.04 Ubuntu kernel on my computer (I had to reformat), and I'm not sure how to install/update. Is there an apt-get command I could use to install the latest java/javac?

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
yes

Titan Coeus
Jul 30, 2007

check out my horn

Hot Yellow KoolAid posted:

Can anybody here who programs Java on linux help me? I have a new 12.04 Ubuntu kernel on my computer (I had to reformat), and I'm not sure how to install/update. Is there an apt-get command I could use to install the latest java/javac?

Not to be a dick but you aren't going to get very far with Linux/programming/life if you don't Google stuff

https://www.google.com/search?q=java+ubuntu

Volguus
Mar 3, 2009

IMlemon posted:

I'm somewhat lost in regards to Spring transaction management, most of the documentation I looked at seems really complex and overwhelming, maybe someone here can dumb it down for me :downs:

Java code:
@Transactional
public void doWork() {
try{
			doDbRelatedWork()
			logSuccessToDb()

		} catch(Exception e) {

			logErrorToDb(e)
		}
}
So, I want to log error cause into db if something goes wrong. The problem is, we're still in the scope of transaction when exception occurs so my logging gets rolled back. Any ideas how I can achieve this?

edit: That makes perfect sense and I have no idea how I could miss that solution.

You can also (but this may not apply to you) have an aspect that would listen further up and log the exception in a different transaction. and just (let's say) annotate the method with your own annotation that could specify what exceptions you're interested in logging, and the aspect would log them for you, all you have to do is annotate the methods.

This method could be a bit cleaner in the long run and if you have a lot of methods that you may want to catch and log the exceptions of, otherwise for very few just catch them further up as it was suggested.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

IMlemon posted:

I'm somewhat lost in regards to Spring transaction management, most of the documentation I looked at seems really complex and overwhelming, maybe someone here can dumb it down for me :downs:

Java code:
@Transactional
public void doWork() {
try{
			doDbRelatedWork()
			logSuccessToDb()

		} catch(Exception e) {

			logErrorToDb(e)
		}
}
So, I want to log error cause into db if something goes wrong. The problem is, we're still in the scope of transaction when exception occurs so my logging gets rolled back. Any ideas how I can achieve this?

edit: That makes perfect sense and I have no idea how I could miss that solution.

A couple things.

1) @Transactional only rolls back by default on unchecked (runtime) exceptions. Also, you can specify exactly what types of exceptions you do want it to rollback for by giving parameters to the annotation - e.g. @Transactional(rollbackFor = RuntimeException.class, MyException.class, ...)

2) Rollback only occurs if the annotated method actually throws. In your code, a rollback should never be triggered, because you're catching all exceptions and not throwing anything.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
php:
<?
public class SomeClass {
  private Map<String, SomeObject> myObjects = new HashMap<String, SomeObject>();

  public Collection<SomeObject> getObjects1() {
    return myObjects.values();
  }

  public Collection<SomeObject> getObjects2() {
    return Collections.unmofidiableCollection(myObjects.values());
  }

  public Collection<SomeObject> getObjects3() {
    return new HashMap<String, SomeObject>(myObjects);
  }
}
?>
Which of these methods is the correct way to be doing things? Or if not one of these, is there something better, such as something that uses .clone()?

Sedro
Dec 31, 2008

fletcher posted:

php:
<?
public class SomeClass {
  private Map<String, SomeObject> myObjects = new HashMap<String, SomeObject>();

  public Collection<SomeObject> getObjects1() {
    return myObjects.values();
  }

  public Collection<SomeObject> getObjects2() {
    return Collections.unmofidiableCollection(myObjects.values());
  }

  public Collection<SomeObject> getObjects3() {
    return new HashMap<String, SomeObject>(myObjects);
  }
}
?>
Which of these methods is the correct way to be doing things? Or if not one of these, is there something better, such as something that uses .clone()?

You don't want to return an object which gives the caller power to mutate myObjects (requirement 1, be friendly to yourself). You also don't return an object which could surprise the caller by changing when they didn't expect it to (requirement 2, be friendly to the consumer).

Method 1 fails requirements 1 and 2.
Method 2 fails requirement 2.
Method 3 doesn't compile.

The easiest solution is to create a copy:
Java code:
public Collection<SomeObject> getObjects() {
    return new ArrayList<SomeObject>(myObjects.values());
}
Guava's immutable collections are also very nice for creating defensive copies of collections and especially when working with constant data.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Awesome, thanks for the tips. Satisfying those requirements makes a lot of sense.

You are certainly correct about method 3 not compiling, oops. Your suggested solution was my intention for that one.

Based on me having a question like that, is there a book that I should pick up that talks about stuff like this?

pigdog
Apr 23, 2004

by Smythe
It depends on the context, too. Sometimes option 1 is right.

Max Facetime
Apr 18, 2009

fletcher posted:

Which of these methods is the correct way to be doing things? Or if not one of these, is there something better, such as something that uses .clone()?

If you know all the people who will be using SomeClass and they won't modify the result of getObjects() or their instance of SomeClass doesn't need to use its insides afterwards, I prefer just returning the objects and refactoring later if needed:

Java code:
public Map<String, SomeObject> getObjects() {
  return myObjects;
}
Otherwise, if there's not too many objects, return an ArrayList<SomeObject> copy to allow users random access indexing into it:

Java code:
public List<SomeObject> getObjects() {
  return new ArrayList<SomeObject>(myObjects.values());
}
Otherwise if there's a whole lot of objects, then return an unmodifiable view to the objects. This one needs extra documentation:

Java code:
/**
 * Returns an unmodifiable view of objects. Changes made to objects by SomeClass
 * are reflected in the returned view. The view is not thread-safe. Etc etc.
 *
 * @return an unmodifiable view of objects.
 */
public Collection<SomeObject> getObjects() {
  return Collections.unmodifiableCollection(myObjects.values());
}
Edit:

fletcher posted:

Based on me having a question like that, is there a book that I should pick up that talks about stuff like this?

Effective Java goes over the API design stuff in Standard Library, especially java.util.* pretty well.

Max Facetime fucked around with this message at 00:04 on Oct 12, 2012

Doctor w-rw-rw-
Jun 24, 2008

Sedro posted:

Guava's immutable collections are also very nice for creating defensive copies of collections and especially when working with constant data.

Seconding this and quoting it specifically to highlight this. Using Guava's immutable collections sends at least two strong, obvious messages: "this collection won't change" and "don't gently caress with this collection, even internally". It gives you a builder so you can clearly define the point at which the data is set in stone, and depending on your circumstances, the immutable collections are more performant than their mutable counterparts. There's no temptation to make some changes to a collection and hope something isn't trying to concurrently access, because modifying the collection involves swapping it out for a different one.

In general, though, I may be biased because I believe it is easier to reason about code in which the data can be relied upon to be static, and when you use immutability to good effect, you can reduce the surface area of mutable state for you to keep in mind when writing your code.

Doctor w-rw-rw- fucked around with this message at 00:38 on Oct 12, 2012

Max Facetime
Apr 18, 2009

Doctor w-rw-rw- posted:

In general, though, I may be biased because I believe it is easier to reason about code in which the data can be relied upon to be static, and when you use immutability to good effect, you can reduce the surface area of mutable state for you to keep in mind when writing your code.

This is a very valuable principle and I don't think you need to invest heavily to reap the benefits. I find that following the object lifetime convention of:

1. construction -> 2. time of frequent state changes[*] -> 3. handing-off of -> 4. time of read-only access -> 5. garbage collection

gives almost all of the good bits of immutable objects (and dare I say functional programming) without any additional effort. To simplify further, as long as you don't change objects you didn't create yourself your own thread keeps state changes at manageable levels.

[*] for an object graph stage 2 of the root node encompasses all of the stage 2's of the child nodes.

1337JiveTurkey
Feb 17, 2005

One of the benefits of final fields over non-final fields is that so long as another thread doesn't access the field within the constructor (and you're doing something seriously wrong if that's the case) the field will always have the initialized value. Non-final fields don't have that guarantee and need an explicit memory barrier of some sort. If you publish the object using a volatile field and all the other threads access the object at least for the first time through the same volatile field, that should be safe.

Opulent Ceremony
Feb 22, 2012

Sedro posted:

Java code:
public Collection<SomeObject> getObjects() {
    return new ArrayList<SomeObject>(myObjects.values());
}

Why does this not allow the original SomeObjects within myObjects to be modified? I'm just assuming that the new ArrayList will copy the references of the SomeObjects from myObjects.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Yeah that's a shallow copy and is useful if your SomeObject class is immutable. If SomeObject class is mutable then you have to do a deep copy.

There is a difference between making the list of your objects immutable and making the objects themselves immutable. Consider carefully what combination of these do you need.

Max Facetime
Apr 18, 2009

Making things actually immutable is a lot more work than deciding not to mutate things that should be immutable.

Doctor w-rw-rw-
Jun 24, 2008

Win8 Hetro Experie posted:

Making things actually immutable is a lot more work than deciding not to mutate things that should be immutable.

Guava makes it easy. And I can turn a couple of variable declarations into an immutable POJO within a minute, including a builder, thanks to code generation. Good enough for me.

Adbot
ADBOT LOVES YOU

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
I am trying to use a while loop to print out a table of conversions of pounds to kilograms (and vice versa).

Example:

Kilograms Pounds | Pounds Kilograms
1 2.2 | 20 9.06
3 6.6 | 25 11.33

197 433.4 | 510 231.03
199 437.8 | 515 233.30

Why am I getting this error message?

quote:

java.util.IllegalFormatConversionException: d != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at ConvertWeights.main(ConvertWeights.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)



I imagine the trouble is the line I have bolded down here.

quote:

//////////////////////////////////////////////////////////////////////////////////
// Displaying Giant Table of Doom
//
// Program that displays the a table of weights in kg. and lbs.
// Example
//Kilograms Pounds | Pounds Kilograms
//1 2.2 | 20 9.06
//3 6.6 | 25 11.33
//…
//197 433.4 | 510 231.03
//199 437.8 | 515 233.30

//import scanner
import java.util.Scanner;

//class name
public class ConvertWeights
{
public static void main(String[] args)
{

//Set up scanner
Scanner input = new Scanner(System.in);

int initialKG = 1;
int initialLB = 20;
float convKG;
float convLB;


System.out.println("Kilograms Pounds | Pounds Kilograms");
System.out.println(initialKG + " " + (initialKG * 2.2) + " |
" + initialLB + " " + (initialLB * .453));

while ((initialKG < 199) && (initialLB < 515)){
initialKG = initialKG + 1;
initialLB = initialLB + 5;
convKG = (float)(initialKG * 2.2);
convLB = (float)(initialLB * .453);
System.out.printf("%d", initialKG + " %.1f", convKG + " |
%.0f", initialLB + " %d", convLB);


}
}
}

Any help would be appreciated.

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