"how do i Check if the Entered Value is a Integer? and if it is, Then only rest of the Code gets Executed ..."
The typical recommendation is to use the Integer#parseInt method.
This method will throw NumberFormatException for non-numeric values, so you can utilize a try-catch block.
Scanner Obj = new Scanner(System.in);
String a = Obj.next();
try {
int value = Integer.parseInt(a);
} catch (NumberFormatException exception) {
}
Here is a relevant StackOverflow question and answer regarding this approach.
StackOverflow – What's the best way to check if a String represents an integer in Java?.
If you are checking only integers, you can use the String#chars method on a.
The Character#isDigit method will return true for '0'
though '9'
.
isInteger = a.chars().allMatch(Character::isDigit);
Or, you can also use the String#matches method.
This uses a regular expression pattern, as a String parameter.
if (a.matches("\\d+"))
"... it should print "Please Enter a Integer Value : "
and asks the user to enter another input. ..."
In this case, start isInteger as false, and set it to true from the other if block.
"... Expected output of the above code:
*
**
***
****
You're going to want to use print, instead of println.
for (j = 1; j <= i; j++) {
System.out.print('*');
}
System.out.println();
Here is the full code,
System.out.println("Enter the Number you want the Maximum times the Pattern to Print while Increasing 1 each Time :");
boolean isInteger = false;
do {
Scanner Obj = new Scanner(System.in);
String a = Obj.next();
// The Condition I want is to check if INPUT 'a' has a integer value and execute rest of the code on the condition.
if (a.matches("\\d+")) {
int i, length = Integer.parseInt(a);
for (i = 1; i <= length; i++) {
int j;
for (j = 1; j <= i; j++) {
System.out.print('*');
}
System.out.println();
}
isInteger = true;
} else {
System.out.println("Please Enter a Integer Value : ");
}
} while (isInteger == false);
Output
Enter the Number you want the Maximum times the Pattern to Print while Increasing 1 each Time :
4
*
**
***
****
Here is how I would write the same code.
Scanner scanner = new Scanner(System.in);
String string;
int value, count;
boolean exit = false;
while (!exit) {
string = scanner.nextLine();
if (!string.matches("\\d+"))
System.out.printf("invalid entry '%s'%n", string);
else {
value = Integer.parseInt(string);
for (count = 1; count <= value; count++)
System.out.println("*".repeat(count));
exit = true;
}
}