import java.util.Scanner;
public class MatchesMethodTest {
public static void main(String[] args) {
String s;
Scanner input = new Scanner(System.in);
System.out.print("Input one real number to one decimal place and one natural number(ex. 1.4 5): ");
s = input.next();
if (s.matches("\\f{1} \\d{1}$"))
System.out.print("You input correctly.");
else
System.out.print("You input incorrectly.");
}
}
The user should input one real number to one decimal place and one natural number. The program prints whether user inputs correctly or not. So when I input 1.4 and 5, I want the program to print “You input correctly”, but it outputs “You input incorrectly” instead. How can I fix this problem?
In a regular expression,
\fdoesn’t match a floating point number, as you seem to want it to do – it matches a special kind of character called the “form-feed character.”Try changing your regular expression match to:
This checks for a single digit, a period, a digit, a space, and a final digit. (Note that your “natural number” is limited to one digit by the
{1}term.)Edit: You may also need to change
input.next()toinput.nextLine(), since the.next()method may only grab the first integer. Untested.