java怎么创建以个函数,java:我怎样才能创建一个支持任意数量参数的函数?

is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ?

thanks

kfir

解决方案

Like this...

public void func(String ... strings) {

for (String s : strings)

System.out.println(s);

}

Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. For example, if you had a function that needed at least one string, and then a variable length argument list:

public void func2(String s1, String ... strings) {

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我们可以定义一个Circle类来表示圆,然后在这个类中实现一个静态方法来判断两个圆的关系。 以下是一个示例代码: ```java public class Circle { private double centerX; private double centerY; private double radius; public Circle(double centerX, double centerY, double radius) { this.centerX = centerX; this.centerY = centerY; this.radius = radius; } public static String getRelation(Circle circle1, Circle circle2) { double distance = Math.sqrt(Math.pow(circle1.centerX - circle2.centerX, 2) + Math.pow(circle1.centerY - circle2.centerY, 2)); if (distance > circle1.radius + circle2.radius) { return "两圆相离"; } else if (distance < Math.abs(circle1.radius - circle2.radius)) { return "一个圆在另一个圆内"; } else if (distance == circle1.radius + circle2.radius) { return "两圆相切外部"; } else if (distance == Math.abs(circle1.radius - circle2.radius)) { return "两圆相切内部"; } else { return "两圆相交"; } } } ``` 我们在Circle类中定义了三个私有属性:圆心的x坐标、圆心的y坐标和半径。然后我们实现了一个静态方法getRelation,它接受两个Circle对象作为参数,并返回一个字符串,表示两个圆的关系。 在getRelation方法中,我们首先计算了两个圆心之间的距离。然后根据距离和半径的关系判断两个圆的位置关系。如果距离大于两个圆的半径之和,那么两个圆相离;如果距离小于两个圆的半径之差,那么一个圆在另一个圆内部;如果距离等于两个圆的半径之和,那么两个圆相切外部;如果距离等于两个圆的半径之差,那么两个圆相切内部;否则两个圆相交。 我们可以在主函数中测试一下: ```java public static void main(String[] args) { Circle circle1 = new Circle(0, 0, 5); Circle circle2 = new Circle(10, 0, 5); String relation = Circle.getRelation(circle1, circle2); System.out.println(relation); } ``` 这里我们定义了两个圆,一个位于原点,半径为5,另一个位于(10,0),半径也为5。我们调用getRelation方法来计算它们的位置关系,并将结果输出到控制台上。运行程序,我们可以看到输出了"两圆相离"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值