Форум программистов, компьютерный форум, киберфорум
Java SE (J2SE)
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.96/76: Рейтинг темы: голосов - 76, средняя оценка - 4.96
nana2002

Преобразование Римский цифр в Арабские и обратно. Вопрос.

16.04.2011, 01:05. Показов 14913. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день. В интернете нашла вот такой код, но разобраться в нем не могу. Точнее не могу разобраться в main классе. Помогите пожалуйсто написать main класс. Спасибо.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
 public class RomanNumeral {
    
       private final int num;   // The number represented by this Roman numeral.
       
       /* The following arrays are used by the toString() function to construct
          the standard Roman numeral representation of the number.  For each i,
          the number numbers[i] is represented by the corresponding string, letters[i].
       */
       
       private static int[]    numbers = { 1000,  900,  500,  400,  100,   90,  
                                             50,   40,   10,    9,    5,    4,    1 };
                                          
       private static String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC",
                                           "L",  "XL",  "X",  "IX", "V",  "IV", "I" };
          
    
       public RomanNumeral(int arabic) {
             // Constructor.  Creates the Roman number with the int value specified
             // by the parameter.  Throws a NumberFormatException if arabic is
             // not in the range 1 to 3999 inclusive.
          if (arabic < 1)
             throw new NumberFormatException("Value of RomanNumeral must be positive.");
          if (arabic > 3999)
             throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
          num = arabic;
       }
       
    
       public RomanNumeral(String roman) {
             // Constructor.  Creates the Roman number with the given representation.
             // For example, RomanNumeral("xvii") is 17.  If the parameter is not a
             // legal Roman numeral, a NumberFormatException is thrown.  Both upper and
             // lower case letters are allowed.
             
          if (roman.length() == 0)
             throw new NumberFormatException("An empty string does not define a Roman numeral.");
             
          roman = roman.toUpperCase();  // Convert to upper case letters.
          
          int i = 0;       // A position in the string, roman;
          int arabic = 0;  // Arabic numeral equivalent of the part of the string that has
                           //    been converted so far.
          
          while (i < roman.length()) {
          
             char letter = roman.charAt(i);        // Letter at current position in string.
             int number = letterToNumber(letter);  // Numerical equivalent of letter.
             
             if (number < 0)
                throw new NumberFormatException("Illegal character \"" + letter + "\" in roman numeral.");
                
             i++;  // Move on to next position in the string
             
             if (i == roman.length()) {
                   // There is no letter in the string following the one we have just processed.
                   // So just add the number corresponding to the single letter to arabic.
                arabic += number;
             }
             else {
                   // Look at the next letter in the string.  If it has a larger Roman numeral
                   // equivalent than number, then the two letters are counted together as
                   // a Roman numeral with value (nextNumber - number).
                int nextNumber = letterToNumber(roman.charAt(i));
                if (nextNumber > number) {
                      // Combine the two letters to get one value, and move on to next position in string.
                   arabic += (nextNumber - number);
                   i++;
                }
                else {
                      // Don't combine the letters.  Just add the value of the one letter onto the number.
                   arabic += number;
                }
             }
             
          }  // end while
          
          if (arabic > 3999)
             throw new NumberFormatException("Roman numeral must have value 3999 or less.");
             
          num = arabic;
          
       } // end constructor
       
    
       private int letterToNumber(char letter) {
             // Find the integer value of letter considered as a Roman numeral.  Return
             // -1 if letter is not a legal Roman numeral.  The letter must be upper case.
          switch (letter) {
             case 'I':  return 1;
             case 'V':  return 5;
             case 'X':  return 10;
             case 'L':  return 50;
             case 'C':  return 100;
             case 'D':  return 500;
             case 'M':  return 1000;
             default:   return -1;
          }
       }
       
    
       public String toString() {
             // Return the standard representation of this Roman numeral.
          String roman = "";  // The roman numeral.
          int N = num;        // N represents the part of num that still has
                              //   to be converted to Roman numeral representation.
          for (int i = 0; i < numbers.length; i++) {
             while (N >= numbers[i]) {
                roman += letters[i];
                N -= numbers[i];
             }
          }
          return roman;
       }
       
       public int toInt() {
            // Return the value of this Roman numeral as an int.
          return num;
       }   
    } // end class RomanNumeral


вот Main класс

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 public class RomanConverter {
    
       public static void main(String[] args) {
          
          TextIO.putln("Enter a Roman numeral and I will convert it to an ordinary");
          TextIO.putln("arabic integer.  Enter an integer in the range 1 to 3999");
          TextIO.putln("and I will convert it to a Roman numeral.  Press return when");
          TextIO.putln("you want to quit.");
          
          while (true) {
    
             TextIO.putln();
             TextIO.put("? ");
             
             /* Skip past any blanks at the beginning of the input line.
                Break out of the loop if there is nothing else on the line. */
             
             while (TextIO.peek() == ' ' || TextIO.peek() == '\t')
                TextIO.getAnyChar();
             if ( TextIO.peek() == '\n' )
                break;
                
             /* If the first non-blank character is a digit, read an arabic
                numeral and convert it to a Roman numeral.  Otherwise, read
                a Roman numeral and convert it to an arabic numeral. */
                
             if ( Character.isDigit(TextIO.peek()) ) {
                int arabic = TextIO.getlnInt();
                try {
                    RomanNumeral N = new RomanNumeral(arabic);
                    TextIO.putln(N.toInt() + " = " + N.toString());
                }
                catch (NumberFormatException e) {
                    TextIO.putln("Invalid input.");
                    TextIO.putln(e.getMessage());
                }
             }
             else {
                String roman = TextIO.getln();
                try {
                    RomanNumeral N = new RomanNumeral(roman);
                    TextIO.putln(N.toString() + " = " + N.toInt());
                }
                catch (NumberFormatException e) {
                    TextIO.putln("Invalid input.");
                    TextIO.putln(e.getMessage());
                }
             }
    
          }  // end while
          
          TextIO.putln("OK.  Bye for now.");
    
       }  // end main()
       
    } // end class RomanConverter
Как я поняла TextIO.putln это System.println.
а в остальном не могу разобраться. помогите пожалуйста.
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
16.04.2011, 01:05
Ответы с готовыми решениями:

Перевод римские цифры в арабские и обратно
Помогите решить задачу на C++ перевод римские цифры в арабские и обратно. PLEASE.

Вопрос преобразование цифр
Существуетли в VB функция преобразование цифр на слов? Например: 224 (двести двадцать четыре). Если не существует, как можно...

Перевод римских цифр в арабские
Суть программы. Вводим с клавиатуры римское число, а нам выводит его арабский вариант. Пример: ввели MMXXII, вывело 2022. Самая сложная...

2
52 / 52 / 10
Регистрация: 25.05.2010
Сообщений: 182
17.04.2011, 00:48
какой именно код вызывает вопрос ? есть ли у Вас хотя бы базовые знания по java ?
0
nana2002
17.04.2011, 06:24
Цитата Сообщение от time2die Посмотреть сообщение
какой именно код вызывает вопрос ? есть ли у Вас хотя бы базовые знания по java ?
Спасибо. Я уже разобралась.
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
17.04.2011, 06:24
Помогаю со студенческими работами здесь

Перевод римских цифр в арабские
Очень нужна программа на visual studio 10(или хотя бы 6) перевода современных чисел кириллические, римские, кто знает как сделать? П.п...

Перевод римских цифр в арабские
Нужно написать программу перевода римских чисел в арабские. Есть эта программа на c#, но нужна на c++. Помогите пожалуйста, горю! Вот эта...

Перевести число из римских цифр в арабские
Здравствуйте! Помогите пожалуйста написать программу, которая переводит число из римских цифр в арабские. Например...

Написать обратный перевод из римских цифр в арабские
Помогите написать обратный перевод, из римских в арабские(10-ую систему) function IntToRoman(Value: LongInt): String; const ...

Преобразование текста в байты и обратно
Необходимо считать строку текста, получить последовательность байт, провести некоторые преобразования, вновь получить на выходе...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru