首页 > 其他分享 >罗马数字的两种写法

罗马数字的两种写法

时间:2023-03-19 12:33:39浏览次数:31  
标签:两种 String int number 罗马数字 str 写法 public

 1 package com.itheima.stringdemo;
 2 
 3 import java.util.Scanner;
 4 
 5 public class StringDemo9 {
 6     public static void main(String[] args) {
 7         //转换罗马数字
 8         //输入一个字符串
 9         String str;
10         while (true) {
11             Scanner sc = new Scanner(System.in);
12             System.out.println("请输入一个字符串");
13             str = sc.next();
14             boolean flag = check(str);
15             if(flag){
16                 break;
17             }else {
18                 continue;
19             }
20         }
21 
22         //1.长度小于等于 9,2.只能是数字
23         //校验字符串要写成方法
24         //将内容转换为罗马数字(方法)
25         //Ⅰ-1、Ⅱ-2、Ⅲ-3、Ⅳ-4、Ⅴ-5、Ⅵ-6、Ⅶ-7、Ⅷ-8、Ⅸ-9、Ⅹ-10
26         //罗马数字里没有0 键入为0时,可以变成" " (长度为0的字符串)
27         StringBuilder sb = new StringBuilder();
28         for (int i = 0; i < str.length(); i++) {
29             //以字符形式接收
30             char c = str.charAt(i);
31             //转换为数字
32             int number = c - 48;
33             //转换为罗马数字,调用并接收
34             String s = changeRoman(number);
35             //接收后拼接 用append
36             sb.append(s);
37         }
38         System.out.println(sb);
39     }
40 
41     //str.length 报错,在循环为无法使用,所以将上面的str写外面
42     //int number 是要改变的数字
43     public  static String changeRoman(int number){
44         //直接定义一个数组来对应 1 --壹
45         String[] s = {" ","Ⅰ","Ⅱ","Ⅲ","Ⅳ","Ⅴ","Ⅵ","Ⅶ","Ⅷ","Ⅸ"};
46         return s[number];
47     }
48 
49     public static boolean check(String str){
50         if(str.length()>9){
51             return false;
52         }
53         for (int i = 0; i <str.length() ; i++) {
54             char c = str.charAt(i);  //返回字符
55             if(c<'0'||c>'9'){
56                 return false;
57             }
58         }
59         //当前字符串判断完
60         return true;
61     }
62 }
1     //利用switch匹配  jdk8以上支持
2     /*public static String changeRoman(char number){
3         String str = switch(number){
4             case '0'->" ";
5             default -> str = "";
6         }
7         return  str;
8     }
9     */

 

标签:两种,String,int,number,罗马数字,str,写法,public
From: https://www.cnblogs.com/Wang0626/p/17232825.html

相关文章