Java 我们是否只在main方法中使用字符串参数?
为什么不能这样使用字符串参数? 在这里,我在readAttributes方法中使用字符串args[]来读取main函数外部的输入。这显示了一个编译错误。我想通过关键字传递参数,而不是使用字符串args从main方法传递参数。需要进行哪些更改Java 我们是否只在main方法中使用字符串参数?,java,Java,为什么不能这样使用字符串参数? 在这里,我在readAttributes方法中使用字符串args[]来读取main函数外部的输入。这显示了一个编译错误。我想通过关键字传递参数,而不是使用字符串args从main方法传递参数。需要进行哪些更改 class rectangle { int l,b; public void area_rect(int l,int b) { System.out.print(+(l*b)); } public
class rectangle
{
int l,b;
public void area_rect(int l,int b)
{
System.out.print(+(l*b));
}
public void perimeter_rect(int l,int b)
{
System.out.print(+(2*(l+b)));
}
***public void readAtrributes(String args[])
{
int l=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
}***
}
public class rec
{
public static void main(String args[])
{
readAttributes ra=new readAttributes();
area_rect ar=new area_rect();
perimeter_rect pr=new perimeter_rect();
}
}
readAttributes是一个方法,但您尝试将其初始化为类
即使是,您仍然必须将实际字符串数组作为参数传递。在Java args中,包含作为字符串对象数组提供的
换句话说,如果您以
java程序运行程序
one-two,那么参数将包含[“one”,“two”]
readAttributes
是一个方法,并且您从中创建了一个对象,因此您会得到编译错误
您必须以这种方式调用这些方法
public static void main(String args[]) {
// creating an object from class rectangle
rectangle rect = new rectangle();
// calling methods of that object
rect.readAtrributes(args);
rect.area_rect(12, 12);
rect.perimeter_rect(10, 12);
}
出现错误是因为尝试将方法用作类,而不是因为该方法。这不是
String[]
作为参数的问题,而是基本java语言的问题。阅读教程readAtrributes()
,area\u rect()
,permiture\u rect()
都是方法。不是一门课。不能使用方法创建对象(违反java原则)。首先,您必须使用类创建一个对象,然后您可以调用“readatributes()”方法。