键盘输入一个字符串:
1.长度小于等于九
2.只能是数字,将内容转换为罗马数字(0转换为"")
package example;
import java.util.Scanner;
public class demo04 {
public static void main(String[] args) {
//录入字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个合法的字符串:");
String str = sc.nextLine();
//字符串是否满足要求
while (true) {
if (check(str)) {
System.out.println("字符串合法");
break;
} else {
System.out.println("不合法,请重新输入:");
str = sc.nextLine();
}
}
//将内容变为罗马数字;1-Ⅰ,2-Ⅱ
String[] result = new String[str.length()];
for (int i = 0; i < str.length(); i++) {
result[i]=changeLuoMa(str.charAt(i));
}
//讲结果打印出来
for (int i = 0; i < result.length; i++) {
System.out.print(result[i]);
}
}
public static boolean check(String str) {
if (str.length() > 9) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) <= '0' || str.charAt(i) >= '9') {
return false;
}
}
return true;
}
public static String changeLuoMa(char c) {
String[] arr={"","I","Ⅱ","Ⅲ","Ⅳ","Ⅴ","Ⅵ","Ⅶ","Ⅷ","Ⅸ"};
int num=c-48;
return arr[num];
}
}
//利用ASCⅡ码将字符转化为数字
//'0'-0