今天在写一个作业,不让用scanner接收数据,要用args[ ]的数组。
public static void main(String args[]) 这一般是我写main这个类最常写的一句话,但是其实我也一直不知道那个String args[]写来是干什么的。但是今天就恰好用上了。
首先,贴一个代码,注意length参数和width参数的接收
//Determine if the args[] is empty
if (args.length == 0)
{
System.out.println("There were no commandline arguments passed!");
}
else
{
// read the data
double length = Double.parseDouble(args[0]);
double width = Double.parseDouble(args[1]);
// Calculate the area of a rectangle
double area = length * width;
// Calculate the perimeter of a rectangle
double perimeter = 2 * (width + length);
// Calculate the diagonal of a rectangle
double diagonal = Math.sqrt(length * length + width * width);
System.out.println("The area of this rectangle is " + area);
System.out.println("The perimeter of this rectangle is " + perimeter);
System.out.println("The diagonal of this rectangle is " + diagonal);
}
如果使用scanner是这样的:
Scanner input = new Scanner(System.in);
// read the data
System.out.println("input the length of a rectangle");
double length = input.nextDouble(); //read length
System.out.println("input the width of a rectangle");
double width = input.nextDouble(); //read width
主要说下如何使用这个args【】,首先他是一个string 的数组,通过先人为的一次性输入他的值,然后通过解析给之后我们coding中的变量,比如,我上段代码种的double length = Double.parseDouble(args[0]);,就是读取args[0]的第一个值,解析为double类型给变量length。
两种方式给args数组赋值,第一种dos命令;第二种eclipse。
①在 DOS中:
传递参数的命令 java Test(ProgramName) args[0] args[1] args[2] ……
程序可以采用的参数数量没有限制,但顺序很重要。JRE按照它们在命令行中出现的顺序传递参数。
args[0]是数组的第一个元素(上面的value1), args[1]是第二个元素(value2),以此类推。length()代码定义了数组的长度。
如第二行
②在Eclipse中:
在run中,找到run configurations,然后找到你代码中的类,然后在argument中输入你要给args[]的值。
在argument中输入你要传参的数据,需要几个就在此处填写几个数据即可。
然后使用double length = Double.parseDouble(args[0]);进行数据的解析。
当在此处填写完5,5 后,就相当于是length = width = 5;
刚刚那个程序的结果就是
然后再说下Integer.parseInt() 和Double.parseDouble()函数的作用
Integer.parseInt(String)的作用就是将String字符类型数据转换为Integer整型数据。
Double.parseDouble(String)函数的作用就是将String字符类型数据转换为double类型的数据。
参考:https://zhidao.baidu.com/question/1957633019096013060.html
https://www.php.cn/java-article-414541.html