* Asks user for a number between low and high (inclusive), reads it and returns
ID: 3807795 • Letter: #
Question
* Asks user for a number between low and high (inclusive), reads it and returns it.
* Read from the provided Scanner and write too the PrintStream
* Keeps reading until user enters a number within range (inclusive). USE a while (or do-while) loop
* @param in - The Scanner to read from
* @param low - the lowest acceptable number
* @param high - the highest acceptable number
* @return the number read
* Your implementation needs to use a while or do-while loop
*/
public static int readWithinRange(Scanner in, PrintStream out, int low, int high)
{
return 0;
Explanation / Answer
ReadNumInrange.java
package org.students;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class ReadNumInrange {
public static void main(String[] args) throws Exception {
//Declaring variables
int low,high;
int number=0;
//Scanner object is used to get the inputs entered by the user
Scanner in=new Scanner(System.in);
//Getting the minimum number
System.out.println("Enter the minimum value :");
low=in.nextInt();
//Getting the maximum number
System.out.println("Enter the maximum value :");
high=in.nextInt();
FileOutputStream fout=new FileOutputStream("D: umbs.txt");
PrintStream out=new PrintStream(fout);
//calling the method to read the number
number=readWithinRange(in,out,low,high);
//This loop continues to execute until the user enters a number within the range
while(number>=low && number<=high)
{
//Printing the data to the output stream file
out.println(number);
//calling the method to read the number
number=readWithinRange(in,out,low,high);
}
out.close();
fout.close();
}
//reading the number from the user within the range
private static int readWithinRange(Scanner in, PrintStream out, int low,
int high) {
System.out.print("Enter a number between "+low+"-"+high+":");
return in.nextInt();
}
}
______________
output:
Enter the minimum value :
5
Enter the maximum value :
50
Enter a number between 5-50:25
Enter a number between 5-50:35
Enter a number between 5-50:45
Enter a number between 5-50:15
Enter a number between 5-50:33
Enter a number between 5-50:44
Enter a number between 5-50:55
______________
num.txt (We can save this file under D Drive.As we specified the path of the output file as D: umb.txt )
25
35
45
15
33
44
____________
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.