I'm learning using an Array and Command line argument for Java. We write a program that convert from Celsius degree to Fahrenheit degree. I started a basic idea for my project but not sure I did it right (I'm beginner).
public class Implementation
{
public static void main(String[] args)
{
{
String[] days = new String[7];
days[0] = "Very Cold";
days[1] = "Cold";
days[2] = "Mild";
days[3] = "Very Mild";
days[4] = "Warm";
days[5] = "Very Warm";
days[6] = "Hot";
}
if (args.length != 5)
{
System.out.println("Error! Please try again.");
System.exit(0);
}
else
{
String name;
String convert;
double degree;
String celsius;
String fahrenheit;
name = args[0];
convert = args[1];
degree = Double.parseDouble(args[2]);
celsius = args[3];
fahrenheit = args[4];
System.out.printf("%n%s Celsius is %.2f Fahrenheit\n", args[2], ( 9.0 / 5.0 * (degree + 32)));
}
}
}
When I supply my command line argument, it should be in this form:
Java TempConversion 100 cf
My questions are: Did I do my command line arguments right? It seem like I did something wrong even though I still have the same output. How do I show up my array in the output with specific degree? Follow this:
Below 0 degrees = Very cold
From 0 to 32 = Cold
From 33 to 50 = Mild
From 51 to 60 = Very mild
From 61 to 70 = Warm
From 71 to 90 = Very warm
Above 90 = Hot
A couple of things:
"Java" and the program name (TempConversion) aren't arguments. Everything after that is. So when you put args.length != 5 you weren't counting the program name and the java keyword. You should use args.length != 3 (as opposed to 5).
Edit:
A question was asked as to how to get the program name and java keyword.
To find the class name you can see this post. Here is my implementation. Should work.
This likely won't cause you much grief, but I don't see a reason for those brackets starting around String[] days and ending at day[6] =...; " }". There isn't a need for them and String[] can have elements that are set and used anywhere (No braces required). Everything else looks fine.
In java TempConversion 100 cf
your command line arguments are 100
and c
and f
-- there are three arguments, but you are checking for five arguments in if (args.length != 5)
This is unlike C where argv[0]
is the program name itself.
You can see this with a minimal program
public class c2f
{
public static void main(String[] args)
{
System.out.println("args.length is " + args.length);
for (int i=0; i<args.length; i++) {
System.out.println("arg[" + i + "] is " + args[i]);
}
}
}
Run this as
javac c2f.java
java c2f 100 c f
Your output should be
args.length is 3
arg[0] is 100
arg[1] is c
arg[2] is f
You are also not looking at either the "c" or the "f" arguments. Maybe you intend to add to your program so those tell you if you want to do a C->F or a F->C conversion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.