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

Objectives To perform while (or do-while) loops. To input a number until valid.

ID: 3699017 • Letter: O

Question

Objectives

To perform while (or do-while) loops.

To input a number until valid.

Prerequisites

Do this problem after you have completed the Conditional Expression programs and are ready to tackle simple while loops.

Description

Write a program (inRange.scala) that asks the user for two integers, A and B, and then asks the user for an integer within the range of A and B (inclusive). It should continue to ask the user for an integer until it is valid (within the range). If A is greater than B, the two numbers should be swapped (exchanged).

Sample Run

The following are some sample runs. It includes both input and output. For clarity, the input lines are preceded by the symbol > and the shell command (to start the program) is preceded by the symbol $. A sample input and output are separated afterwards.

Input

Here is just a sample input to the program.

Output

Here is just a sample output to the program. Notice that the prompts are part of the program's output.

Hint

You will want to use the following Scala language features:

StdIn.readInt to read in integer values

if statement to check various conditions

while (or do-while) to repeat a sequence of statements while a condition is true (such as while the input is invalid).

need in scala

Explanation / Answer

object inRange {

def main(args: Array[String]) {

var a,b,d=1;

println("Please enter two numbers defining the range.");

a=scala.io.StdIn.readInt();

b=scala.io.StdIn.readInt();

if(a>b)

{

a=a+b;

b=a-b;

a=a-b;

}

do

{

println("Please enter a number between " + a + " and " + b);

val c=scala.io.StdIn.readInt();   

if(c>b || c<a)

{

println("That number is not between " + a + " and " + b);

d=0;

}

else

{

println("The number " + c+ " is between " + a + " and " + b);

d=1;

}  

}while(d==0);

  

}

}