如何解决Java:如何重构代码以减少冗余?
//这是我的代码,我在问我是否可以重复m的步骤而不必重写。
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");
解决方法
正如洛克在评论中提到的那样,您可以使用函数来重构代码以减少冗余。例如,我将创建一个类似这样的函数:
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("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");
我希望你有主意。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。