2 Replies - 8370 Views - Last Post: 11 February 2012 - 02:19 PM Rate Topic: -----

#1 gcurrier  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 9
  • Joined: 07-April 10

Roman to Arabic number conversion

Posted 28 May 2010 - 12:30 PM

What follows is the work I have (so far ) completed for a Homework assignment, part of which is mine and part of which I have had help with previously.

The first problem I have is with a label within a panel. How do I get the text to wrap? For now I have to resize the first window in order to see the whole text.

Secondly, I have created an event listener to close a window and open another (visible vs. not). The first window remains open, while the second window opens at its smallest dimensions (setSize IS used but ineffective).

Third, the panels used in both windows are (more or less) carbon copies yet the panel resizing in the second window is not the same as the first (I think it should be, the way it is written, I'm not sure why it acts the way it does)

Finally, the number crunching protion of the program is complete and it works, I'm just losing it on how to connect it to the Application GUI.

The way it is supposed to work is that a user will enter a number to convert. Upon the button click the converted amount will display in the appropriate text field.
Here are the code sheets
Title Window
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ConverterTitle extends JFrame{
  
  public ConverterTitle(){

    //pnlA Components - frame1: title window
    JPanel pnlA1 = new JPanel(new FlowLayout());
    pnlA1.setBackground(Color.white);
    JPanel pnlA2 = new JPanel(new FlowLayout());
    pnlA2.setBackground(Color.white);
    JPanel pnlA3 = new JPanel(new FlowLayout());
    pnlA3.setBackground(Color.white);
    JPanel pnlA4 = new JPanel(new GridLayout(3,0,0,3));
    pnlA4.setBackground(Color.white);
    ImageIcon title_image = new ImageIcon("title.jpg");
    JLabel lblA = new JLabel("Welcome.  This application will convert Arabic numbers to " +
            "Roman Numerals and vice versa.  The limits are from 1 to 3000 (Arabic).  An " +
            "error is thrown when an ivalid amount is entered.  To continue, press the " +
            "button below.  Enjoy!");
    //ListenerClass listen = new ListenerClass();
    JButton btnExit = new JButton("Exit");
    btnExit.setToolTipText("Clicking this button exits the program.");
    JButton btnCont = new JButton("Continue");
    btnCont.setToolTipText("Clicking this button will take you to the main application");
    
    

    pnlA1.add(new JLabel(title_image, SwingConstants.CENTER));
    pnlA2.add(lblA);
    pnlA3.add(btnCont, BorderLayout.CENTER);
    pnlA3.add(btnExit, BorderLayout.CENTER);

    pnlA4.add(pnlA1);
    pnlA4.add(pnlA2);
    pnlA4.add(pnlA3);
    add(pnlA4, BorderLayout.CENTER);

    btnCont.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        JFrame appGUI = new ConverterApp();
        JFrame titleGUI = new ConverterTitle();
        if (e.getActionCommand().equalsIgnoreCase("Continue")){
          appGUI.setVisible(true);
          titleGUI.setVisible(false);
        }
      }
    });
    btnExit.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        if (e.getActionCommand().equalsIgnoreCase("Exit")){
          System.exit(0);
        }
      }
    });
  }
  
}


Application Window
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ConverterApp extends JFrame{
  public ConverterApp(){

    ListenerClass listen = new ListenerClass();
    Font font = new Font("Verdana", Font.BOLD, 16);

    JPanel pnlB0_0 = new JPanel(new GridLayout(1,1));
    pnlB0_0.setBackground(Color.WHITE);

    JPanel pnlB0_1 = new JPanel(new GridLayout(1,1));
    pnlB0_1.setBackground(Color.WHITE);

    JPanel pnlB0_2 = new JPanel(new GridLayout(2,1));
    pnlB0_2.setBackground(Color.WHITE);
    pnlB0_2.setBorder(BorderFactory.createLineBorder(Color.black, 1));

    JPanel pnlB0_3 = new JPanel(new GridLayout(1,0,3,3));
    pnlB0_3.setBackground(Color.WHITE);

    JPanel pnlB0_4 = new JPanel(new GridLayout(2,2));
    pnlB0_4.setBackground(Color.WHITE);

    JPanel pnlB0_5 = new JPanel(new FlowLayout());
    pnlB0_5.setBackground(Color.WHITE);

    JPanel pnlB1_0 = new JPanel(new GridLayout(1,1));
    pnlB1_0.setBackground(Color.WHITE);

    JPanel pnlB1_1 = new JPanel(new GridLayout(1,1));
    pnlB1_1.setBackground(Color.WHITE);

    JPanel pnlB1_2 = new JPanel(new GridLayout(2,1));
    pnlB1_2.setBackground(Color.WHITE);
    pnlB1_2.setBorder(BorderFactory.createLineBorder(Color.black, 1));

    JPanel pnlB1_3 = new JPanel(new GridLayout(1,0,3,3));
    pnlB1_3.setBackground(Color.WHITE);

    JPanel pnlB1_4 = new JPanel(new GridLayout(2,2));
    pnlB1_4.setBackground(Color.WHITE);

    

    JLabel lblB1 = new JLabel("Convert between number systems");
    JLabel lblB2 = new JLabel("Enter an English number between 1 and 3000: ");
    JTextField txt1 = new JTextField(20);
    txt1.setFont(font);
    JButton btnToRoman = new JButton("Convert to Roman");
    btnToRoman.setToolTipText("Convert to Roman Numerals");
    btnToRoman.addActionListener(listen);
    ImageIcon english = new ImageIcon("english_num.gif");
    
    pnlB0_0.add(new JLabel(english, SwingConstants.LEFT));
    pnlB0_1.add(lblB1, BorderLayout.WEST);
    pnlB0_2.add(lblB2);
    pnlB0_2.add(txt1);
    pnlB0_3.add(btnToRoman);
    pnlB0_4.add(pnlB0_0);
    pnlB0_4.add(pnlB0_1);
    pnlB0_4.add(pnlB0_2);
    pnlB0_4.add(pnlB0_3);
    
    add(pnlB0_4, BorderLayout.NORTH);


    JLabel lblB3 = new JLabel("Enter a Roman number between I and MMM: ");
    JTextField txt2 = new JTextField(20);
    txt2.setFont(font);
    JButton btnToEnglish = new JButton("Convert to English Numbers");
    btnToEnglish.setToolTipText("Convert to English Numerals");
    btnToEnglish.addActionListener(listen);
    ImageIcon roman = new ImageIcon("roman_num.gif");

    pnlB1_0.add(new JLabel(roman, SwingConstants.LEFT));
    pnlB1_2.add(lblB3, BorderLayout.WEST);
   
    pnlB1_2.add(txt2);
    pnlB1_3.add(btnToEnglish);
    pnlB1_4.add(pnlB1_0);
    pnlB1_4.add(pnlB1_1);
    pnlB1_4.add(pnlB1_2);
    pnlB1_4.add(pnlB1_3);

    add(pnlB1_4, BorderLayout.CENTER);

    JButton btnAppExit = new JButton("Exit");
    btnAppExit.setToolTipText("Clicking this button exits the program.");
    pnlB0_5.add(btnAppExit, BorderLayout.CENTER);

    add(pnlB0_5, BorderLayout.SOUTH);

    btnAppExit.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        if (e.getActionCommand().equalsIgnoreCase("Exit")){
          System.exit(0);
        }
      }
    });

  }
  private static class ListenerClass implements ActionListener {
    public void actionPerformed(ActionEvent e){
      JFrame titleGUI = new ConverterTitle();
      JFrame appGUI = new ConverterApp();
      if (e.getActionCommand().equalsIgnoreCase("Convert to Roman Numerals")){
      //point to converter program
      }
      if (e.getActionCommand().equalsIgnoreCase("Convert to English Numbers")){
      //point to converter program
      }

    }
  }

}


Converter Program
public class ConverterMain{

  private final int num;

  //two arrays: numbers and letters with corresponding indices
  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 ConverterMain(int english){
  
    if (english < 1)
      throw new NumberFormatException("Number must be positive.");
    if (english > 3000)
      throw new NumberFormatException("Number must be 3000 or less.");
    num = english;
  }

  public ConverterMain(String roman){
    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;       
    int arabic = 0;  

    while (i < roman.length()){
      // Letter at current position in string.
      char letter = roman.charAt(i);     
      int number = RomanToArabic(letter);  //Numerical equivalent of letter.
      if (number < 0)
        throw new NumberFormatException("Illegal character \"" + letter + "\" in roman numeral.");
      //Move to next position in the string
      i++;
      if (i == roman.length()){
        arabic += number;
      }
      else{
        //if the next letter has a larger equivalent than the variable number,
        //both letters are counted together
        int nextNumber = RomanToArabic(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{
          arabic += number;
        }
      }
    }
    if (arabic > 3000)
      throw new NumberFormatException("Roman numeral must have value 3000 or less.");
    num = arabic;
    }


  private int RomanToArabic(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;
    }
  }



  @Override
  public String toString() {
    String roman = "";  // The roman numeral.
    //N represents the part of num that still has to be converted to Roman numeral representation.
    int N = num;
    for (int i = 0; i < numbers.length; i++) {
      while (N >= numbers[i]) {
        roman += letters[i];
        N -= numbers[i];
      }
    }
    return roman;
  }

  public int toInt() {
    // Return value of roman numeral
    return num;
  }
} 


Executor
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class NumberConverter {
  public static void main(String[] args) {

        //Create a Frame
        JFrame titleGUI = new ConverterTitle();
        titleGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        titleGUI.setTitle("Currier Project 3: Number Converter Title");
        titleGUI.setSize(400,300);
        //no window resizing
        titleGUI.setResizable(false);
        titleGUI.setLocationRelativeTo(null);
        titleGUI.setVisible(true);

        JFrame appGUI = new ConverterApp();
        appGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        appGUI.setTitle("Currier Project 3: Number Converter Application");
        appGUI.setSize(500,500);
        //no window resizing
        appGUI.setResizable(false);
        appGUI.setLocationRelativeTo(null);
        appGUI.setVisible(false);


          }
  
}


Thanks for any tips you may provide.

Is This A Good Question/Topic? 1
  • +

Replies To: Roman to Arabic number conversion

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10185
  • View blog
  • Posts: 37,603
  • Joined: 27-December 08

Re: Roman to Arabic number conversion

Posted 28 May 2010 - 07:14 PM

Problem 1- JLabels will not wrap text. You can use JTextArea instead and setEditable(false).

Problem 2- I think this is due to poor design. If you have instances of both frames in one class, and you create instnaces of both frames in your main() method, you aren't going to get the desired result. The sole purpose of main() should be to start your program. That is it. If you want to include the two frame classes within another class, that's fine. Just make sure that you have them set up to display appropriately. Don't then instantiate them in main() as well.

Problem 3- What are you expecting vs. the result? What panel for what class is not acting accordingly?

Problem 4- You have to create an instnace of your Converter class in the appropriate GUI class, and invoke its converter methods passing the appropriate params.
Converter c = new Converter(2000); //for example
System.out.println(c); //toString() displays roman numeral
System.out.println(c.toInt()); //toInt() displays arabic numeral


Was This Post Helpful? 1
  • +
  • -

#3 vdarko  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 11-February 12

Re: Roman to Arabic number conversion

Posted 11 February 2012 - 02:19 PM

I needed JSF Converter from Arabic to Roman numerals and vice versa.I modified code from above, works like a charm!
Below is Java Class, just add it to your faces-config.xml and thats it ;-)
Methods Roman2Arabic(String roman) and Arabic2Roman(Integer arabic) are static, just pass them parameters :bananaman:

@gcurrier You have all regards!


package rs.schedule.web.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * Calculates numbers between 0 and 3000
 * */
public class ArabicRomanConverter implements Converter{

	//two arrays: numbers and letters with corresponding indices
	private final static int[]    numbers = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
	private final static String[] letters = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

	public static Integer Roman2Arabic(String roman){
		if (roman.length() == 0)
			return null;

		roman = roman.toUpperCase();  // Convert to upper case letters.
		int i = 0;       
		int arabic = 0;  

		while (i < roman.length()){
			// Letter at current position in string.
			char letter = roman.charAt(i);     
			int number = letterToNumber(letter);  //Numerical equivalent of letter.
			if (number < 0)
				throw new NumberFormatException("Illegal character \"" + letter + "\" in roman numeral.");
			//Move to next position in the string
			i++;
			if (i == roman.length()){
				arabic += number;
			}
			else{
				//if the next letter has a larger equivalent than the variable number,
				//both letters are counted together
				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{
					arabic += number;
				}
			}
		}
		if (arabic > 3000)
			return null;
		return arabic;
	}

	public static String Arabic2Roman(Integer arabic) {
		String roman = "";  // The roman numeral.
		//arabic represents the part of num that still has to be converted to Roman numeral representation.
		for (int i = 0; i < numbers.length; i++) {
			while (arabic >= numbers[i]) {
				roman += letters[i];
				arabic -= numbers[i];
			}
		}
		return roman;
	}

	private static 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 static void main(String[] args){
		System.out.println(Roman2Arabic("XXVI"));
		System.out.println(Arabic2Roman(26));
}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		
		Integer arabic = Roman2Arabic(value);
		
		return arabic;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		
		Integer arabic = (Integer) value; 
		String roman = Arabic2Roman(arabic);
		
		return roman;
	}

}



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1