Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java Write a method printRange that accepts integer parameters x and y and th

ID: 3575983 • Letter: I

Question

In Java

Write a method printRange that accepts integer parameters x and y and that prints the sequential integers between x and y inclusive. The first half should be printed with the greater-than character (">") separating consecutive values. The second half should be printed with the less-than character ("<") separating consecutive values. The following table shows several calls and their expected output:

Notice that in the first output, 5 is in the middle with the numbers before it separated by greater-than and the numbers after it separated by less-than. In the second output, 14 is in the middle with numbers before it separated by greater-than and numbers after it separated by less-than. The third output has no separators because that range includes one number. When there are two values in the middle of the range, those two values should be separated by a dash, as shown in the last two outputs.

The method should throw an IllegalArgumentException if x is greater than y.

Output should look exactly like this:

test #1:printRange(1, 9);

expected output:1 > 2 > 3 > 4 > 5 < 6 < 7 < 8 < 9

Call Output printRange(1, 9); 1 > 2 > 3 > 4 > 5 < 6 < 7 < 8 < 9 printRange(10, 20); 10 > 11 > 12 > 13 > 14 > 15 < 16 < 17 < 18 < 19 < 20 printRange(-8, -8); -8 printRange(1, 10); 1 > 2 > 3 > 4 > 5 - 6 < 7 < 8 < 9 < 10 printRange(13, 14); 13 - 14

Explanation / Answer


public class pricePrint {
   public static void printRange(int x,int y) throws IllegalArgumentException
   {
       if(x>y)
       {
           throw new IllegalArgumentException("The value of x cannot be greater than y.");
       }
       int num = y-x+1;
       int mid = (y-x+1)/2;
       System.out.print(x);
       for(int i=x+1;i<x+mid;i++)
       {
           System.out.print(">"+i);
       }
       if(num%2==0)
       {
           System.out.print("-"+(x+mid));
           mid++;
       }
       else
       {
           System.out.print(">"+(x+mid));
           mid++;
       }
       for(int i=x+mid;i<=y;i++)
       {
           System.out.print("<"+i);
       }
       System.out.println("");
   }
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       printRange(1, 10);
       printRange(1, 9);
       printRange(10,20);

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote