Convert Roman numbers to Java

Asked

Viewed 2,185 times

2

I made a program that converts whole numbers to Roman numbers in Java, but the program does not run.

What can it be?

Follows the code:

import java.util.Scanner;

public class Teste {

    public static void main(String[] args) {

        Scanner teclado = new Scanner(System.in);

        int numero, i;
        int vaNum[]= {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        String vaRom[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

        while(true){

            numero = teclado.nextInt();
            if(numero == 0)
                break;
            System.out.printf("%-4d", numero);
            i=0;
            while(numero>0){
            if(numero >= vaNum[i]){
                System.out.println(vaRom[i]);
                numero = numero - vaNum[i];
            }
            }

        }
    }
  • I think all you need is the primary symbols of the Roman numbers (I,v,x,L,c, d and m) and how much they represent in decimals and then in which positions they appear when grouped. Doing this makes it easy to convert.

1 answer

4


You forgot to increment the i within the while internal when the number cannot be subtracted. This causes this while inner be infinite.

There were also small problems of using System.out.println instead of System.out.print, which would add line breaks after each character.

See here your corrected code:

import java.util.Scanner;

class Teste {

    public static void main(String[] args) {

        Scanner teclado = new Scanner(System.in);

        int[] vaNum = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};

        String[] vaRom = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

        while (true) {

            int numero = teclado.nextInt();
            if (numero == 0) break;
            System.out.printf("%-4d ", numero);
            int i = 0;
            while (numero > 0) {
                if (numero >= vaNum[i]) {
                    System.out.print(vaRom[i]);
                    numero -= vaNum[i];
                } else {
                    i++;
                }
            }
            System.out.println();
        }
    }
}

Given this entry:

4999
237
88
23
0

It produces this output:

4999 MMMMCMXCIX
237  CCXXXVII
88   LXXXVIII
23   XXIII

See here working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.