java - 从内部切换 case 语句和运行方法
问题描述
我在开关盒中使用随机数。所以有类似的东西:
public void something {
Random myRand = new Random();
int number = myRand.nextInt(10 - 1) + 1;
switch(number)
case 1:
Do something and on completion go back and start running the something method again.
break:
case 1;
Do something and on completion go back and start running the something method again.
break;
每个 case 语句可以根据用户的输入运行任意次数,有些甚至可能不使用。
我想要的是案例声明中的内容:-
public void something (run);
我正在尝试做的事情是可能的还是有更好的方法?
解决方案
我可以建议你使用接口吗?您尝试实现的内容称为函数式编程,其中您将函数作为参数传递给另一个函数
java通过使用接口以某种方式支持函数式编程,并且具有许多内置接口来简化流程
我建议你看看 java.util.function 包
现在让我们开始你的代码
public void something(Supplier<Void> function) {
boolean condition = true; //use this boolean to control your loop
while (condition) {
Random myrand = new Random();
int number = myrand.nextInt(10 - 1) + 1;
switch (number) {
case 1:
function.get();
break;
case 2:
function.get();
break;
}
}
}
你可以这样称呼你的“东西”
public void Call() {
//if you want to declare the function only once
something(new Supplier<Void>() {
@Override
public Void get() {
System.out.println("the job is done!");
return null;
}
});
// if you already have a class implementing supplier
something(new MyFunction());
}
并不是因为您的函数没有任何输入而使用了 Supplier 接口,您还可以使用 Consumer、BiConsumer、Function、BiFunction .... 用于具有输入的函数
推荐阅读
- node.js - Gulp 脚本不存在
- ruby-on-rails - postgres - distinct order_by 一个 jsonb 键抛出一个 rails PG::InvalidColumnReference
- node.js - 如何通过一条 HTTP Post 消息也传递 FormData 和其他变量?(角度,节点)
- node.js - 使用 Node.js 和 MongoDB 完成回调执行后如何执行新函数?
- arrays - 具有多个条件和重复值的索引匹配功能
- android - onActivityResult中访问ViewHolder参数
- google-compute-engine - 谷歌云 - 计算引擎
- jquery - 输入键的数据列表
- oracle11g - 当我们移动到下一页并返回复选框页面时,如何保存选定的复选框值并使其选中
- python - 在 Python 中迭代地调用它们之间的脚本和变量