Convert Roman numbers in Java

2

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

What can it be?

Follow 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];
            }
            }

        }
    }
    
asked by anonymous 19.10.2017 / 19:51

1 answer

4

You forgot to increment the i within% internal% when the number can not be subtracted. This causes this while internal to be infinite.

There were also minor issues with using while instead of System.out.println , which would add line breaks after each character.

See your corrected code here:

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.

    
19.10.2017 / 20:22