Page 1 of 1

Java a beginner's guide's a modified example

Posted: Thu Aug 04, 2011 1:41 pm
by Nipuna
I am now referring Java a beginner's guide book. :)

Code: Select all

/*
Project 1-1
This program converts gallons to liters.
Call this program GalToLit.java.
*/

class GalToLit {

    public static void main(String args[]) {

        double gallons; // holds the number of gallons

        double liters; // holds conversion to liters

        gallons = 10; // start with 10 gallons

        liters = gallons * 3.7854; // convert to liters

        System.out.println(gallons + " gallons is " + liters + " liters.");
}
}

I've modified it as this. To get user inputs. I know one way of giving inputs :) That is giving values via parameters :) Not a so clever coding isn't it? ;)

Code: Select all


class GalToLit{

   public static void main(String args[]){

      double gallons,liters;

      gallons = Double.parseDouble(args[0]);

      liters = gallons*3.7854;

      System.out.println(gallons+" gallons is "+ liters + " liters. ");
      

}
}




How is it? :)

PS: I had to add codes without syntax heightening since that function doesn't work. May be because of the server changing

Re: Java a beginner's guide's a modified example

Posted: Thu Aug 04, 2011 3:15 pm
by Neo
Syntax highlighting works now. However to get it working correctly, you will have to use Tab for indents.

Also, taking you to another step... ;)
How if someone enters a text value there instead of a floating point number? It will give you an error. Here is how you could handle that.

Code: Select all

try{
	gallons = Double.parseDouble(args[0]);
	
	liters = gallons * 3.7854;
	System.out.println(gallons+" gallons is "+ liters + " liters. ");	
}
catch (NumberFormatException e){
	System.out.println("Input must be a number!");
}

Re: Java a beginner's guide's a modified example

Posted: Thu Aug 04, 2011 3:19 pm
by Nipuna
Great.

And another thing.

2 Smilies are not working

clap and laughing

By the way now Expertcore is working fast :)

Re: Java a beginner's guide's a modified example

Posted: Thu Aug 04, 2011 3:27 pm
by Neo
By the way now Expertcore is working fast :)
Thanks Nipuna.
Smilies are not working
New smileys are back.

Notice my code mod with exception handling.

Re: Java a beginner's guide's a modified example

Posted: Thu Aug 04, 2011 3:33 pm
by Nipuna
Wow! Cool ! You filled one of my memory gaps. :biggrin:

You are right, When learning concepts and in systematically, it's getting easy . :yahoo: