7-2 sdut-JAVA-Words Containing AB
分数 9
全屏浏览
切换布局
作者 马新娟
单位 山东理工大学
Write a program that requests a word as input containing the two letters a and b (in this order). Examples of valid words would include, abacus, cab, and anybody, whereas invalid words would include branch, back, and bank. You should only concern yourself with the first occurrence of a and b should they exist.
Input Specification:
a word as input containing the two letters a and b (in this order).
Output Specification:
Output the input word is valid or not.
Sample Input:
Sample Output:
No input provided to check.
Sample Input:
about12
Sample Output:
Input should comprise of alphabetic characters only.
Sample Input:
about
Sample Output:
about is valid
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String arr=sc.nextLine(); if(arr.isBlank()) { System.out.println("No input provided to check."); System.exit(0); } if(!arr.matches("[a-zA-Z]+")) { System.out.println("Input should comprise of alphabetic characters only."); System.exit(0); } int indexA=arr.indexOf('a'); int indexB=arr.indexOf('b'); if(indexA!=-1&&indexB!=-1&&indexA<indexB) { System.out.println(arr+" is valid"); } else { System.out.println(arr+" is not valid"); } sc.close(); } }