Question

Write a static method named containsClosePair that accepts a Scanner object as a parameter. The method...

Write a static method named containsClosePair that accepts a Scanner object as a parameter. The method should read three, and only three, integers from the Scanner and returns true if there is (at least) one pair of those three integers that differ exactly by 1. For example, the integers 1 and 2 differ by 1, so entering the three integers "1 5 2" containing the pair 1 and 2 would return true. The integers 12 and 11 also differ by 1. Your method should return false if there are no such values separated by exactly 1 in the user input. The user always inputs 3 valid integers separated by spaces. You do not need to print a prompt for the user.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;

public class ClosePair {

    public static boolean containsClosePair(Scanner in) {
        int n1 = in.nextInt();
        int n2 = in.nextInt();
        int n3 = in.nextInt();
        return Math.abs(n1 - n2) == 1 || Math.abs(n2 - n3) == 1 || Math.abs(n1 - n3) == 1;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println(containsClosePair(in));
        in.close();
    }

}
Add a comment
Know the answer?
Add Answer to:
Write a static method named containsClosePair that accepts a Scanner object as a parameter. The method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT