In: Computer Science
Create a project with a Program class and write the following two methods (headers provided) as described below:
Java code given below :-
import java.util.*;
import java.io.*;
public class HelloWorld{
public static int InputValue(int min, int max)
{
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Enter a number."); // get a number
String input = in.next();
int number = 0;
try {
number = Integer.parseInt(input); // convert string to
integer
if(number>=min && number<=max) // if
number between lower bound and upper bound(inclusive)
{
System.out.println("number is valid.");
}
else
{
while (number< min || number >max) // if number not between
lower bound and upper bound(inclusive)
{
System.out.println("re-enter a number :"); // re-enter number
number = in.nextInt();
}
System.out.println("number is valid.");
}
break;
}
catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue"); // if user
enter a non-number
}
}
return 0;
}
public static boolean IsValid(String id)
{
char[] sArr = id.toCharArray(); // convert given
string to char array
boolean x=false;
if(sArr.length==5) // if length of array is 5
then
{// check given string is valid or not
if( ('A'<=sArr[0] &&
sArr[0]<='Z') && ('A'<=sArr[1] &&
sArr[1]<='Z') && ('0'<=sArr[2] &&
sArr[2]<='9') && ('0'<=sArr[3] &&
sArr[3]<='9') && ('0'<=sArr[4] &&
sArr[4]<='9'))
{
x=true;
}
else{
x=false;
}
}
else{ // if length of array is not 5
x=false;
}
return x; // return boolean value
}
public static void main(String []args){
Scanner in = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.println("Enter a lower bound :"); // get lower
bound
int lower =
in.nextInt();
System.out.println("Enter a upper bound :"); // get upper
bound
int upper =
in.nextInt();
InputValue(lower,upper);
// call InputValue() function
System.out.println("\nEnter a
String :"); // get String
String str =
sc.nextLine();
boolean x =IsValid(str); // call
IsValid() function
if(x==true)
{
System.out.println("valid String."); // if string is
valid
}
else{
System.out.println("In-valid String."); // if string is
in-valid
}
}
}
Screenshot of code and output :-