Input parameters in java - java

I was wondering why do Java programs take parameters only in the form on Strings from the command line when they are run? I have read that if the parameters are declared as int, it still converts the int into String. Why does this happen? And is there any way to accept only int values from the command line when running a java program?

Strings are more versatile as they can hold any value and can even be an representative as an int. If you want to pass an int in the command line you can convert the string to and int yourself.
int val = Integer.parseInt(arg[0]);
The valid signature for the main method is
public static void main(String[] args)
no other argument structure will be seen as a main function.

I have read that if the parameters are declared as int, it still converts the int into String.
You have read that incorrectly. If the main() method takes anything other String[] args, it won't be recognized as a valid entry point by the JVM.
If you wish to take integer arguments, your main method still has to accept String[] args, and you have to perform the conversion yourself.

You passing chars from command line anyway (just because there is no "integers" on keyboard). So, you need to convert this char arrays (which are wrapped into String) into integers.

Related

Java: Making an Optional Command Line Argument

I am working on a program that is supposed to take one required command line argument and one optional command line argument. The first argument is the name of an output file where data will be written to, and the second is a number that will be used to calculate the data to be written to the output file. If the user does not enter a number, then it should just use a default value to calculate the data. For example, if the user entered command line arguments "Foo.csv 1024" the program would use 1024 to calculate the data and write it to Foo.csv, but if the user only used the command line argument "Foo.csv" then the program would use a default value of 2048 to calculate the data and write it to Foo.csv. I am creating/running this program using the Intellij IDE. How would I do this? Any advice/suggestions would be much appreciated.
Your program seems to be simple, so the solution is also simple for this particular case. You can test how many arguments were passed to the program checking the argument args of your main function:
public static void main(String[] args){...}
args is an array that contains the arguments passed to your program. So if your program is called prog and you run it with prog Foo.csv 1024, then args will have:
args[0] = "Foo.csv";
args[1] = "1024";
With this, you know which arguments were passed to your program and by doing args.length, you can know how many they were. For the example above, args.length=2 If the user didn't indicate the last argument ("1024"), then you would have args.length=1 with the following in args:
args[0] = "Foo.csv";
So your program would be something like:
public static void main(String[] args){
//The default value you want
int number = 2048
if(args.length==2){
number = Integer.parseInt(args[1]);
}
//'number' will have the number the user specified or the default value (2048) if the user didn't specify a number
}
To supply arguments to your program you must run it on a console or some kind of terminal. Using IntelliJ (or any other IDE) it's also possible to run the program with arguments, but you specify those in the Run Settings.
If you want a more complex treatment of arguments, usually what you want is done by argument parsers. These are usually libraries that take you argv and help you reading arguments to your program. Among other things, these libraries usually support optional arguments, arguments supplied via flags, type checking of arguments, creating automatic help pages for your commands etc. Consider using an argument parser if your argument requirements are more complex or if you just want to give a professional touch to your program :)
For java i found this particular library: http://www.martiansoftware.com/jsap/doc/

Returning all strings from an array after a specific index

I have made a command that does something to a player. One of the optional arguments for this is to add a reason and when executed, it would be sent to the user.
The problem is, I have created the command and the reason works however, the reason has to be written with no spaces. (e.g YouWereGreifing!). This is because in the code I have only told it to use the argument with the index of a number.
My question is, how would I combine an array into a string, but only take the values after a certain index in that array.
Code
Here is the method I am calling:
Main.demotePlayer(player, targetPlayer, "Guest", args[1])
and the args[] is being created with
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String [] args){
Try the Arrays.copyOfRange method?
newarray[] = Arrays.copyOfRange(oldArray, start, oldArray.length);

Clarifying this Java "Activity" from "SamsTeachYourself Java"

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?
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.

How to implement overload methods to identify variables correctly

I've been working on my project for about 15 hours straight and I ran out of ideas and am in desperate need of some help. I have looked at tutorials and books, but i cannot figure it out.
My main problem is that i cannot understand/calculate how i can use an overload method to choose between an int or a double. To explain I'm trying to get my program to use user input to convert the value to either int to a double (or vice-versa) and store the result to show the correct answers.
Instead of just leaving it as double I'm trying to get the variation for each possibility.
The reason I'm trying to do so is as follows (i know the code doesn't need it but the assignment requires i do so in this way but I keep hitting dead ends) :
Here’s where the overloading comes in: some applications will define the amount as an int, and others will define it as a double. Therefore, you need to write two overloaded versions of this method:
Get user input only once. If you convert the input value for the amount loaned to an int and store it in an int variable, you can then convert the value of this int to a double and store the result of this conversion in a double variable. The use of cast operators to either convert int values to double or double values to int.
Why complicating the situation?
A simple solution:
- Receive the input as double
- Check whether the number is integer. If yes then convert it to integer then call the appropriate method. A quick search give this:
How to test if a double is an integer
Convert double to Int, rounded down
If you need to write two overloaded versions of the interestcalc function, just make two separate methods with the following signatures:
public static void interestcalc (int aLoan, double interes, int numYears)
{
// perform calculations here
}
public static void interestcalc (double aLoan, double interes, int numYears)
{
// perform calculations here
}

Why does Java takes Input in String format only?

In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not require methods to convert them. Then why does java follows such long procedure. **What is the reason behind such an architecture of Java ?
//In java we follow the following process
public static void main(String args[])
{int i = Integer.parseInt( args[0]);// here we get input in String format and then convert it
}
//In C++ we follow the following :
void main()
{int i;
cin>>i;
}
Both C/C++ and Java takes input form Console then why java takes it in String Format and C++ does not ??
Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Java - If you use the Scanner class you can get the input in the required data type. It's not only String java accepts.
If you take an integer from the console in C, it will require you to atoi() the input.
You always get a string when reading from stdin. In C++ however, the >> operator overload used when writing to an int performs the conversion - so it's just a different way of converting but in both languages it's necessary.
You are right that it's nicer in C++ though since you can use pretty much the same code no matter what data type you have.

Categories