Issue
//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");
Solution
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.
Answered By - Gursewak Singh
Answer Checked By - Timothy Miller (JavaFixing Admin)