Reputation: 171
I want to ask the size of the array from the user. If the user does not enter the size and press the enter button, I want to use array size as 10 (default value). I am not able to do it. Here is my simple java code.
System.out.print("Enter the size of Stack: "); int size = sc.nextInt();
Check out the image for reference.
I am a beginner in java.
Upvotes: 2
Views: 823
Reputation: 1860
The problem is, that the sc.nextInt();
is waiting as long as it can find an int
input.
A workaround for your problem could be to read the whole line and then try to parse this line to an int
.
If the user-input is not an int (e.g. abcdefg
or an empty String (only enter-button)), then the parsing will fail. Therefore in the catch
block the default value is set.
E.g. it could look like this:
String sizeString = sc.nextLine();
int size;
try {
size = Integer.parseInt(sizeString);
} catch (NumberFormatException e) {
size = 10;
}
Upvotes: 4
Reputation: 1269
If you use nextLine()
instead of nextInt()
you can check if the enter key was pressed by comparing the input
against an empty string.
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of Stack: ");
// The replaceAll cleans the input by removing all non numeric characters
String input = sc.nextLine().replaceAll("[^0-9]", "");;
int size;
// If the input is empty set size to 10 otherwise parse the string input as an integer
if(input.equals("")){
size = 10;
}else{
size = Integer.parseInt(input);
}
System.out.println(size);
Output:
Enter the size of Stack:
10
Upvotes: 4