我试图避免重复大量的代码,并想知道是否有一个捷径?我想要一个文字快捷方式,它只是用编译中的文本替换快捷方式。
例如:
private int a = 0;
/*Shortcut sc = new Shortcut ( for(a = 0; a < 5; a++) ); */
if (truth = true)
sc.doTask(a);
else
sc.doTask((a+1);
我知道它不会影响编码效率,但会使任务看起来更有条理。
答案 0 :(得分:0)
您尝试做的似乎是让您的代码无法维护且难以阅读(除非您询问如何在函数中组织代码)。 它并不总是与编码效率有关。您必须确保您的代码不易被其他开发人员维护和理解。
如果您想避免重复代码,请将重复的代码放在一些定义良好的方法中。
public class Test {
public static void main(String[] args) {
Test test = new Test();
// Now you can use the so called shortcut that is called a method everywhere you want.
int sum = test.getSum(1, 2, 3);
System.out.println("Sum is " + sum);
// Now again reuse the method instead of loads of code :)
sum = test.getSum(2, 4, 5);
System.out.println("New sum is " + sum);
}
public int getSum(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
}
顺便说一句。你的if(真值=真)是对变量的赋值,称为&#34;真理&#34;并将始终评估为真。你的别人永远不会被召唤。
答案 1 :(得分:0)
生病了。要减少锅炉板代码,您可以使用方法。举个例子
public class MyFooClass {
private int[] numbers;
public void doStuff1() {
// do something
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
public void doOtherStuff() {
// do something
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
}
正如您所看到的,我们检查重复次数2次,我们可以在另一种方法中重复使用该代码。
public class MyFooClass {
private int[] numbers;
public void doStuff1() {
// do something
checkForDuplicatesOrSomething();
}
public void doOtherStuff() {
// do something
checkForDuplicatesOrSomething();
}
private void checkForDuplicatesOrSomething() {
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
}
答案 2 :(得分:-2)
每次打印时都不会调用System.out.println("blah blah blah my text");
,而是可以像这样编写自己的方法。
public void p(Object o) {
System.out.println(o);
}
然后在你的代码中简单地调用这个方法:
String s = "foo";
StringBuilder sb1 = new StringBuilder("i hate this town");
p(s);
p(sb1);