I don't know why this isn't working cause the value of they is still 0 even if I type a sentence that starts with a number, contains "end", and ends with an Upper case letter. Also, this should be case sensitive.
if (sentence.startsWith("[0-9]") && sentence.contains("end") && (sentence.endsWith("[A-Z]"))) {
y++;
}
System.out.println(y);
Your code didn't work because String::startWith doesn't take a regex as a parameter while you are using a regex. You need to use String::matches as shown below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int no = 0;
while (no < 4) {
System.out.print("Type a number >4: ");
no = Integer.parseInt(scan.nextLine());
}
String sentence;
int y = 0;
for (int i = 0; i < no; i++) {
System.out.print("Enter a sentence: ");
sentence = scan.nextLine();
if (sentence.matches("[0-9]+.*end.*[\\p{javaUpperCase}]")) {
y++;
}
}
System.out.println(y);
}
}
A sample run:
Type a number >4: 5
Enter a sentence: Hello world
Enter a sentence: 123 Hello World ends with LD
Enter a sentence: 123HelloendHH
Enter a sentence: Good morning
Enter a sentence: 123Good morning
2