2

In the book "SamsTeachYourself Java" there is a task that goes like this:

"Write a Java application that takes an argument as a string, converts it to a float variable, converts that to a Float object, and finally turns that into an int variable. Run it a few times with different arguments to see how the results change."

Could someone clarify this text, especially the first part about a java application that takes an argument as a string?

TimLinden
  • 117
  • 1
  • 8
  • Read a number(to convert it into float) from command line of data type as a string. – Kaustubh Khare Jul 02 '14 at 13:23
  • This text could probably be phrased better. All java applications take an array of Strings as arguments (the static main method). You could simply pass it via the command line: http://docs.oracle.com/javase/tutorial/getStarted/application/ – JamesB Jul 02 '14 at 13:26

1 Answers1

1

In Java programs start with

public static void main(String[] args){

args is a variable of type String[] (an array of Strings). You can call call functions like args.length() which will return the number of arguments made to the program.

This array is populated with the things that follow the name of the program when you call it. For example if you called your program like:

java MyProgram ate my dog

The variable args would have length three and contain the values "ate", "my", "dog". The following lines would all return true.

args[0].equals("ate");
args[1].equals("my");
args[2].equals("dog");

These other answers will also help explain this

What is "String args[]"? parameter in main method Java

args.length and command line arguments

In IDE like Eclipse you don't type the command that executes these lines but you can configure your project to run with a predetermined set of values. For how to do this in eclipse see this other answer: Eclipse command line arguments


Following the input of a String that represents a float (ex. "1.98") Java contains a number of useful functions for parsing strings into other types. Many of these are contained in classes which wrap the primitive types. One of these is the object type Integer which contains a function called parseInt which takes a String as an argument and returns an int. Similar classes exist for other primitive types as well, including doubles and floats.

Variables of these types can be constructed from their corresponding primitive types. Here is the online documentation of these constructors for the Integer class.


Finally the problem asks you to convert a float to an int. In java you can call a type cast operation like so:
float a = 8.88;
int b = a; //error, loss of precision
int c = (int)a;

When typecasting a float or a double to an int the value is not rounded, it is truncated. In my example above the variable c has a value of 8, not 9.

Community
  • 1
  • 1
Tucker Downs
  • 92
  • 1
  • 11