DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. ## Different Answers to Simple Calculations

Happy New Year all, hope you are all well, I'm have a bit of a problem.... I'm a newbie learner and I'm just writing some simple console applications to get to grips with the basic syntax of Java... I wrote some Java code that converts gallons into cubic feet (don't ask why lol)..... I also done the equivalent in C++
but I'm getting different answers....... Also can some one explain to me how to create simple inputs for integer in Java, (for example "enter 4 here") the book I am using to learn from is a bit cryptic, or if u could point me in the direction of something online that would be a great help

Thanks

Here is my code

public class GallandFeet {

/**
* This is a program to further help solidify my understanding of
data types in Java. This program will take the input from the user
in "gallons" and will output the equivalent in cubic feet.
*/

public static void main(String[] args)
throws java.io.IOException
{

double cubic_Ft = 7.481; // Here I have defined a variable for cubic feet
char c; // This is a variable for the input stream to recognise numbers entered
// by the user

System.out.println("Enter The Amount of Gallons");
c = (char)System.in.read(); // I'm not to sure what I'm doing here I got this from a book ????

double cub_Gall = c * cubic_Ft; // Here is the calculation used to convert gallons into cubic feet

System.out.println("The amount of Cubic feet" + cub_Gall);
// This should display the result of the calculation

}
}

It actually compiles which is a plus but the answer I get is different to the answer I get in my C++ VERSION and I trust that one more lol

Thanks for the help in advance

2. Senior Member
Join Date
Dec 2004
Location
San Bernardino County, California
Posts
1,468
The numeric value of a char will not be the same as the numeric value of the character. The ASCII code for the character "3" is 51 - so the integer value of the char '3' is 51, not 3.

You can cast the value of the char to an int .

However, since you are looking at learning how to handle user input, take a look at the Scanner class provided in the JDK and the methods of that class. You can create a Scanner object which accepts the input, then you can create an "int" [or other kind of input expected] from what the user has typed.

A very good resource for learning how to write effective Java code is the Java Tutorial (and other tutorials) produced and maintained by Sun. You can find the intro to the tutorial at http://java.sun.com/docs/books/tutorial/
Last edited by nspils; 01-02-2010 at 05:54 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise