我是Java的新手,我怎么想才能找到针对这些三个问题 ...
的解决方案我做对的事情(如果我没记错的话):
代码:
import java.util.Scanner;
public class Exercise5 {
public static void main (String [] args){
Scanner scan=new Scanner (System.in);
System.out.println("Write a sentence:");
String sent=scan.nextLine();
if (sent.startsWith("An") && sent.contains("apple") &&
sent.charAt(sent.length()-1)>='0' && sent.charAt(sent.length()-1)<='9'){
System.out.println("The sentence is correct.");
}
else {
System.out.println("Wrong.");
}
}
}
谢谢!
答案 0 :(得分:2)
您可以使用Chain of Responsibility pattern
并检查所有需要的内容。
public abstract class Handler {
private Handler next;
public abstract boolean check(final String str);
protected boolean checkNext(final String str) {
if (next == null) {
return true;
}
return next.check(str);
}
public Handler linkWith(Handler next) {
this.next = next;
return next;
}
}
public class VowelsHandler extends Handler {
private final static int NUM_OF_VOWELS = 9;
private final static List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u');
@Override
public boolean check(String str) {
final boolean result = str.chars().mapToObj(c -> (char)c).filter(vowels::contains).count() <= NUM_OF_VOWELS;
return result && checkNext(str);
}
}
public class WordsHandler extends Handler {
private final static int NUM_OF_WORDS_IN_SENTENCE = 12;
@Override
public boolean check(String str) {
String[] arr = str.split("\\b");
final boolean result = arr.length <= NUM_OF_WORDS_IN_SENTENCE;
return result && checkNext(str);
}
}
public class Main {
private Handler handler;
public static void main(String[] args) {
new Main().start();
}
public void start() {
Handler handler = new VowelsHandler();
handler.linkWith(new WordsHandler());
boolean result = handler.check("a b c d e f g h i j k l m");
System.out.println(result);
}
}
您只需要创建Handler
抽象类的新实现并将其添加到链中即可。
handler.linkWith(new PercentHandler());
答案 1 :(得分:1)
尝试实现此方法
pFrame->data[0]