Reputation:
I want to check if the user inputed in a string, and if he does I want to print it out or warn him to enter a string next time. I know that my problem is with the condition in the if statement but I don't know which method I should use in this case. I use hasNextInt
for Integer
s but from the look of it this doesn't work like I would hope with String
.
EDIT: Just to clarify from the comments: the text should hold only a specific character set like a-z, A-Z and spaces.
import java.util.Scanner;
public class JavaLessonTwoTest {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter string please: ");
if (userInput.hasNext(String("")) {
String stringEntered = userInput.next();
System.out.println("You entered " + stringEntered);
} else {
System.out.println("Enter a string next time.");
}
}
}
Upvotes: 0
Views: 138
Reputation: 3048
A console is a text interface, thus a user can only input data as String
. Given that, you can try to parse the input to an Integer
, Float
, Book
or any other type depending on your needs.
What you are trying to do is probably something like this:
while(true) {
System.out.print("Enter string please: ");
String input = userInput.next();
boolean isInputInt;
try {
int number = Integer.parseInt(input);
// parsing to int succeeded
isInputInt = true;
} catch (NumberFormatException ex) {
// parsing to int failed
isInputInt = false;
}
if (isInputInt) {
System.out.println("Integers are not allowed.");
// retry
continue;
} else {
System.out.println("You entered " + input);
// proceed
break;
}
}
Upvotes: 2
Reputation: 1498
What you probably are searching for, is a Regular Expression.
I'll give you an example, so you have to adapt it to your code:
public class Patt {
public static void main(String... args) {
String[] tests = {
"AA A",
"ABCDEFGH123",
"XXXX123",
"XYZabc",
"123123",
"X123",
"123",
};
for (String test : tests) {
System.out.println(test + " " + test.matches("[a-zA-Z ]*"));
}
}
}
The point is the regular expression
[a-zA-Z ]*
in the call test.matches("[a-zA-Z ]*")
. It means "match only strings that have any number of letters which are either from a
to z
, A
to Z
or whitespace ().
Upvotes: 2
Reputation: 496
According to this: Restrict string input from user
This should work:
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter String only with letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Digits are not allowed");
sc.next();
}
String word = sc.next();
System.out.println("User input was : " + word);
}
Upvotes: 0