Java:如何重构我的代码以减少冗余?

huangapple go评论66阅读模式
英文:

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(&quot;First 3-digit number: &quot;);
        int m = getInput(&quot;Second 3-digit number: &quot;);
        
        
        int n3 = n % 10;
        int n2 = n / 10 % 10;
        int n1 = n / 100 % 10;

        if (n1 == n3) {
            System.out.println( &quot;yes&quot;);
        } else {
            System.out.println( &quot;No&quot;);

I hope, you got the idea.

</details>



huangapple
  • 本文由 发表于 2020年10月4日 12:28:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64191175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定