Write methods in Java to accomplish the tasks listed below. Then, write a main()
ID: 640328 • Letter: W
Question
Write methods in Java to accomplish the tasks listed below. Then, write a main() method that asks the user to input a 4-digit integer, say num, and then calls the four methods in order with num as input and prints the result.
1- public static void displayDigits(int num) This method takes as input a 4-digit number (i.e., an integer between 1000 and 9999) and displays the input number as a sequence of digits, separating each pair of digits by two spaces. For example, displayDigits(2345) prints 2 3 4 5.
2- public static int sumDigits(int num) This method takes as input a 4-digit integer and calculates and returns the sum of digits in the number. For example, sumDigits(2345)returns 14 (2+3+4+5).
3- public static int reverse(int num) This methods takes a 4-digit integer returns as output another number with the same digits but reversed. For example reverse(2345) returns 5432.
4- public static boolean palindrome(int num) This methods takes a 4-digit integer returns as output ture if the input number is a palindrome and false is the input number is not a palindrome. A number is palindrome if the number equals to its reverse. For example, palindrome(1221) returns true however palindrome(2345) returns false.
Sample run:
Enter a 4-digit number: 5678
Digits: 5 6 7 8
Sum digits: 26
Number reversed: 8765
Palindrome: false
Explanation / Answer
This will do the trick, has been tested:
//Palindrome.java
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
while (true) {
display(check(retrieveInput()));
}
}
public static String retrieveInput() {
Scanner scan = new Scanner(System.in);
return scan.next();
}
public static boolean check(String input) {
boolean check = false;
try {
Integer.parseInt(input);
if (input.charAt(0)==input.charAt(4) && input.charAt(1)==input.charAt(3))
check = true;
} catch(Exception e) {
check = false;
}
return check;
}
public static void display(boolean check) {
if(check) System.out.println("Is a five-digit palindrome.");
else System.out.println("Is not a five-digit palindrome.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.