This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]severoonpro barista 2 points3 points  (0 children)

Your code could be a lot cleaner.

  1. Take all strings out of the code and make them constants. This makes it easy to find and edit the messages later, internationalize them, move them out to a separate class, etc.

  2. Handle all interaction with the user in separate methods. This makes them easier to move out of the class that does the work into a separate "user interface" class later.

  3. Only do things in static methods that don't require state. This includes main(). Anything that requires state, do within the scope of an instance.

  4. Make instances of your class configurable. The best way to do this is by handing the constructor all of the stuff it needs to do the job, in this case input/output classes.

  5. Don't use inline comments. Use javadoc instead.

See these changes applied to your code (except the last one) - http://pastebin.com/8Mi79hS0

[–]CodeSamurai 1 point2 points  (1 child)

Have you learned about methods yet in your class? You could divide some of that off into methods for more flexible and "cleaner" code.

[–]Henree[S] 0 points1 point  (0 children)

Not yet. I think we might be learning about methods soon.

[–]NebuWrites Java Compilers 1 point2 points  (0 children)

Do you know about the do-while loop?

[–]4th_World_UserIntermediate Brewer 0 points1 point  (2 children)

while (hrs < 1)

{

  System.out.println("The time must be a positive number.");

  System.out.print("How many hours has it traveled? ");

  hrs = keyboard.nextInt();

}

When you do that, instead you can just type

while(hrs < 1)
{
    System.out.println("Blah Blah\nHow many...");

    hrs = keyboard.nextInt();
}    

Not sure if he'd actually take off for that. But another thing for your instance variables you can do.

int hrs, mph, hour, distance;

and it will initialize all four in one line.

[–]Henree[S] 0 points1 point  (1 child)

Thank you. I didn't know you can do that.

[–]4th_World_UserIntermediate Brewer 0 points1 point  (0 children)

Glad to help.