英文:
Java: How to refactor my code to reduce redundancy?
问题
//这是我的代码,我想知道是否可以在不必重写的情况下重复步骤m次。
Scanner input = new Scanner(System.in);
System.out.print("第一个3位数:");
int n = input.nextInt();
System.out.print("第二个3位数:");
int m = input.nextInt();
int n3 = n % 10;
int n2 = n / 10 % 10;
int n1 = n / 100 % 10;
if (n1 == n3) {
System.out.println("是");
} else {
System.out.println("否");
}
英文:
//Here's my code, I'm asking if I could repeat steps for m without having to rewrite.
Scanner input = new Scanner(System.in);
System.out.print("First 3-digit number: ");
int n = input.nextInt();
System.out.print("Second 3-digit number: ");
int m = input.nextInt();
int n3 = n % 10;
int n2 = n / 10 % 10;
int n1 = n / 100 % 10;
if (n1 == n3) {
System.out.println( "yes");
} else {
System.out.println( "No");
答案1
得分: 0
正如Locke在评论中提到的,您可以使用函数对代码进行重构以减少冗余。例如,我会创建一个如下所示的函数:
public static int getInput(String msg)
{
System.out.print(msg);
int m = input.nextInt();
return m;
}
然后在您的代码中使用该函数,如下所示:
Scanner input = new Scanner(System.in);
int n = getInput("第一个3位数:");
int m = getInput("第二个3位数:");
int n3 = n % 10;
int n2 = n / 10 % 10;
int n1 = n / 100 % 10;
if (n1 == n3) {
System.out.println("是");
} else {
System.out.println("否");
}
希望您明白我的意思。
<details>
<summary>英文:</summary>
As Locke mentioned in the comment, you can use function to refactor your code to reduce the redundancy. For example, I would create a function like so:
public static int getInput(String msg)
{
System.out.print(msg);
int m = input.nextInt();
return m;
}
and use that function in your code like so:
Scanner input = new Scanner(System.in);
int n = getInput("First 3-digit number: ");
int m = getInput("Second 3-digit number: ");
int n3 = n % 10;
int n2 = n / 10 % 10;
int n1 = n / 100 % 10;
if (n1 == n3) {
System.out.println( "yes");
} else {
System.out.println( "No");
I hope, you got the idea.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论