思路:利用数字与数组索引匹配关系
- import java.util.Scanner;
-
- public class test {
- public static void main(String[] args) {
- String str;
- //键盘录入
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个字符串");
- str = sc.next();
- while (true) {
- //校验录入的字符串是否满足要求
- boolean flag = ccc(str);
- if (flag){
- break;
-
- }else {
- System.out.println("不符合规则请重新输入!");
- continue;
- }
- }
- //将内容变成罗马数字
- // 查表法:数字和数组产生对应关系
- StringBuilder sbu = new StringBuilder();
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- int number = c - 48; //48为数字0的编码
- //调用方法进行转换
- String s = change(number);
- //字符串拼接
- sbu.append(s);
-
- }
- //输出
- System.out.println(sbu);
- }
- //查表法的一个方法
- public static String change(int number){
- String[] arr = {"","I ","II ","III ","IV ","V ","VI ","VII ","VIII ","IX "};
- return arr[number];
- }
-
- public static boolean ccc(String str){
- //要求1:长度为小于等于9
- if (str.length() > 9){
- return false;
- }
-
- //要求2:只能是数字
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- if (c < '0' || c > '9'){
- return false;
- }
- }
- //只有当字符串里面所有的字符都判断完毕了 才能认为当前字符串符合规则
- return true;
-
- }
- }
执行效果:
思路:利用switch进行匹配
- import java.util.Scanner;
-
- public class test {
- public static void main(String[] args) {
- String str;
- //键盘录入
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一个字符串");
- str = sc.next();
- while (true) {
- //校验录入的字符串是否满足要求
- boolean flag = ccc(str);
- if (flag){
- break;
-
- }else {
- System.out.println("不符合规则请重新输入!");
- continue;
- }
- }
-
-
- //将内容变成罗马数字
- StringBuilder sbu = new StringBuilder();
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- //调用方法进行转换
- String s = change(c);
- //字符串拼接
- sbu.append(s);
-
- }
- //输出
- System.out.println(sbu);
- }
- //对应法的一个方法
- public static String change(char number){
- String str = switch (number){
- case '0' -> str = "";
- case '1' -> str = "I ";
- case '2' -> str = "II ";
- case '3' -> str = "III ";
- case '4' -> str = "IV ";
- case '5' -> str = "V ";
- case '6' -> str = "VI ";
- case '7' -> str = "VII ";
- case '8' -> str = "VIII ";
- case '9' -> str = "IX ";
- default -> str = "";
- }
- return str;
- }
-
- public static boolean ccc(String str){
- //要求1:长度为小于等于9
- if (str.length() > 9){
- return false;
- }
-
- //要求2:只能是数字
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- if (c < '0' || c > '9'){
- return false;
- }
- }
- //只有当字符串里面所有的字符都判断完毕了 才能认为当前字符串符合规则
- return true;
-
- }
- }
”注意“ 其中 String str = switch (number){ } 为JDK12版本的新特性