(Note this is while loop, no array please and thanks) Write a method called cons
ID: 3640190 • Letter: #
Question
(Note this is while loop, no array please and thanks)Write a method called consecutive that accepts three integers as parameters and returns true if they are three consecutive numbers—that is, if the numbers can be arranged into an order such that, assuming some integer k, the parameters’ values are k, k + 1, and k + 2.
Your method should return false if the integers are not consecutive.
Note that order is not significant; your method should return the same result for the same three integers passed in any order.
Call Returns
consecutive(5, 6, 8); false
consecutive(9, 7, 8); true
consecutive(7, 9, 8); true
Explanation / Answer
import java.util.*;
public class Test {
static void consecutive(int num1, int num2, int num3) {
boolean sequence = false;
int max = Math.max(Math.max(num1, num2), num3);
int min = Math.min(Math.min(num1, num2), num3);
int middle = 0;
if (num1 == num2 && num1 == num3) {
middle = num1; // it doesnt what the value here is..
}
if (max - 1 == num1) {
middle = num1;
}
if (max - 1 == num2) {
middle = num2;
}
if (max - 1 == num3) {
middle = num3;
}
if ((min + 1 == middle) && (min + 2 == max)) {
sequence = true;
}
System.out.println("("+num1+","+num2+","+num3+") : "+sequence);
}
public static void main(String[] args) {
Test.consecutive(0,2,1);
}
}
import java.util.*;
public class Test {
static void consecutive(int num1, int num2, int num3) {
boolean sequence = false;
int max = Math.max(Math.max(num1, num2), num3);
int min = Math.min(Math.min(num1, num2), num3);
int middle = 0;
if (num1 == num2 && num1 == num3) {
middle = num1; // it doesnt what the value here is..
}
if (max - 1 == num1) {
middle = num1;
}
if (max - 1 == num2) {
middle = num2;
}
if (max - 1 == num3) {
middle = num3;
}
if ((min + 1 == middle) && (min + 2 == max)) {
sequence = true;
}
System.out.println("("+num1+","+num2+","+num3+") : "+sequence);
}
public static void main(String[] args) {
Test.consecutive(0,2,1);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.