Results 1 to 5 of 5
  1. #1
    zimbobigdog is offline Member
    Join Date
    Dec 2010
    Posts
    13
    Rep Power
    0

    Default How to loop throug vector

    I am trying to develop a simple translation program and need to know how to loop through a vector and check if an input word matches one of the word elements in the vector. I want to output a translation message to screen only if the word is a match (if the word does not match one of the words in my vector I want to output a different message). The code I have created below does work but it outputs a message for every element in the vector. My code is as follows:

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    public class Vector1
    	{
    	Vector1()
    	{
    	Word wd3 = new Word("englishwd3","frenchwd3","meaning3","engexample3","freexample3");
    	Word wd4 = new Word("englishwd4","frenchwd4","meaning4","engexample4","freexample4");
    	Word wd5 = new Word("englishwd5","frenchwd5","meaning5","engexample5","freexample5");
    	
    	Vector<Word> v = new Vector<Word>();
    
    	v.add(wd3);
    	v.add(wd4);
    	v.add(wd5);
    	
    	String inputword =JOptionPane.showInputDialog(null, "What word would you like to translate into French?");
    	for(int i=0; i < v.size();i++)
    	{
    	Word wd = v.elementAt(i);
    
    	if (inputword.equals(wd.getwdEng()))
    	{
    	
    // create translation message
    	String message1 = String.format(inputword + " is translated as " + wd.getwdFre() + ". The word means " + wd.getmeaning() +
    						". An English example: " + wd.getEngEx() + ". A French example: " + wd.getFreEx());
    
    // output translation message
    		JOptionPane.showMessageDialog( null, message1 );
    	}
    	else
    	{
    // create not in dictionary message
    	String message2 = String.format(inputword + " is not in the dictionary");
    
    // output not in dic message
    	JOptionPane.showMessageDialog( null, message2 );
    	}
    }
    }
    
    public static void main (String[] args) 
    	{
    		// Start the program running from its constructor
    		new Vector1();
    }
    }
    Is there any way I can achieve the single output message after looping through the vector?
    Thanks.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    A separate method may keep the logic clean:

    Java Code:
    import java.util.List;
    import java.util.ArrayList;
    
        /**
         * A class to illustrate the use of a separate method that finds things in
         * a list and which performs different operations depending on whether 
         * or not a match was found.
         */
    public class Test {
    
        private static List<String> list = new ArrayList<String>();
    
            /**
             * Adds some elements to the dictionary and performs a couple
             * of tests of the finding logic.
             */
        public static void main(String[] args) {
            list.add("fee");
            list.add("fie");
            list.add("foe");
            list.add("fum");
    
            lookFor("fie");
            lookFor("field");
        }
    
            /**
             * Prints one message is a given target appears within the
             * list and another if not.
             */
        private static void lookFor(String target) {
            for(String s :list) {
                if(s.equals(target)) {
                    System.out.println(target + " found!");
                    return;
                }
            }
            System.out.println(target + " NOT found!");
        }
    }

    I have preferred the more modern alternatives to the Vector list, and used an enhanced for loop. But the main thing is that the separate method is able to do one thing if a match is found and then return and another thing if it gets all the way through the dictionary without finding a match.

    --------------------

    You could achieve the same result within the main() method by using a boolean "flag": a variable that is set once a match is found, or by declaring i before the for loop starts and breaking out of the for loop when a match occurs and checking the value of i after the loop has finished.

    But the main() method - and every other method - should be kept short: as short as it possibly can be to do the one, single, simple, thing it is documented to do. On this ground alone another method is called for.
    Last edited by pbrockway2; 12-08-2010 at 11:32 PM.

  3. #3
    zimbobigdog is offline Member
    Join Date
    Dec 2010
    Posts
    13
    Rep Power
    0

    Default

    Thanks for the info. I was able to sort that code out and now have a working vector program. I am now trying to extend the program using the Java swing utility. I have spent some hours trying to figure out how to impliment the program and am getting myself all knotted. My code is as follows:
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    
    public class TranslatorInput3
    {
    	JLabel label;
    	public TranslatorInput3()
    	{
    //Create Control Box
    	JFrame frame = new JFrame ("Translator control box");
    	JButton translate = new JButton("Translate a Word");
    	JButton addword = new JButton("Add a Word");
    	JPanel panel = new JPanel();
    		panel.add(translate);
    		panel.add(addword);
    		panel.setBounds(20, 50, 150, 150);
    		translate.addActionListener(new MyAction());
    		translate.setBackground(new java.awt.Color(204, 204, 255));
    		translate.setToolTipText("Click this button to use the Translate function.");
    		addword.addActionListener(new MyAction1());
    		addword.setBackground(new java.awt.Color(204, 204, 255));
    		addword.setToolTipText("Click this button to add a new word to libraryu.");
    		label = new JLabel ("Translation program");
    		frame.add(panel);
        		frame.add(label);
        		frame.setSize(600, 600);
        		frame.setVisible(true);
        		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	}
    
    public class Vector1
    	{
    	public void main(String[] args)
    	{
    	Word wd3 = new Word("englishwd3","frenchwd3","meaning3","engexample3","freexample3");
    	Word wd4 = new Word("englishwd4","frenchwd4","meaning4","engexample4","freexample4");
    	Word wd5 = new Word("englishwd5","frenchwd5","meaning5","engexample5","freexample5");
    	Word wd6 = new Word("englishwd6","frenchwd6","meaning6","engexample6","freexample6");
    	Word wd7 = new Word("englishwd7","frenchwd7","meaning7","engexample7","freexample7");
    	Word wd8 = new Word("englishwd8","frenchwd8","meaning8","engexample8","freexample8");
    	Word wd9 = new Word("englishwd9","frenchwd9","meaning9","engexample9","freexample9");
    	Word wd10 = new Word("englishwd10","frenchwd10","meaning10","engexample10","freexample10");
    	Word wd11 = new Word("englishwd11","frenchwd11","meaning11","engexample11","freexample11");
    	Word wd12 = new Word("englishwd12","frenchwd12","meaning12","engexample12","freexample12");
    	Word wd13 = new Word("englishwd13","frenchwd13","meaning13","engexample13","freexample13");
    
    	Vector<Word> v = new Vector<Word>();
    	
    	v.add(wd3);
    	v.add(wd4);
    	v.add(wd5);
    	v.add(wd6);
    	v.add(wd7);
    	v.add(wd8);
    	v.add(wd9);
    	v.add(wd10);
    	v.add(wd11);
    	v.add(wd12);
    	v.add(wd13);
    	
    	searchVector(v.inputword);
    	}
    	
    	public class MyAction implements ActionListener
    	{
    	public void actionPerformed(ActionEvent e)
    		{
    		String inputword =JOptionPane.showInputDialog(null, "What word would you like to translate into French?");
    			
    		}
    		public void searchVector(Vector<Word> v, String inputword)
    		{
    		for(int i=0;i<v.size();i++)
    		{
    			Word wd = v.elementAt(i);
    			if(wd.getwdEng().equals(inputword))
    			{
    // create translation message
    			String message1 = String.format(inputword + " is translated as " + wd.getwdFre() + ". The word means " + wd.getmeaning() +
    						". An English example: " + wd.getEngEx() + ". A French example: " + wd.getFreEx());
    // output translation message
    			JOptionPane.showMessageDialog( null, message1 );
    			return;
    			}
    		}
    // create not in dictionary message
    		String message2 = String.format(inputword + " is not in the dictionary");
    
    // output not in dic message
    		JOptionPane.showMessageDialog( null, message2 );			
    		}
    	}
    	}
    
    public class MyAction1 implements ActionListener
    	{
    	public void actionPerformed(ActionEvent e)
    		{
    		JOptionPane.showMessageDialog(null,"Adds word to library.");
        		}
    	}
    
    
    public static void main (String[] args)
    	{
    	new TranslatorInput3();
    	}
    }
    I want to have a few buttons doing different tasks but at the moment am just trying to get the translate button working. Am I right to implement the different classes or should I be implementing the vector within my TranlatorInput3 class?

    Please help ;)

  4. #4
    zimbobigdog is offline Member
    Join Date
    Dec 2010
    Posts
    13
    Rep Power
    0

    Default

    Sorry all. I sorted it. Stupid mistake:searchVector(v,inputword); instead of searchVector(v.inputword);

    Next to read the data to and from a file

  5. #5
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by zimbobigdog View Post
    Sorry all. I sorted it. Stupid mistake:searchVector(v,inputword); instead of searchVector(v.inputword);
    Didn't you notice that at compile time?

Similar Threads

  1. Vector<vector> loop thru
    By ocean in forum New To Java
    Replies: 11
    Last Post: 11-21-2009, 02:17 PM
  2. Vector
    By sanox in forum New To Java
    Replies: 20
    Last Post: 09-01-2009, 04:21 PM
  3. Replies: 1
    Last Post: 04-06-2009, 06:45 AM
  4. vector - get
    By natdizzle in forum New To Java
    Replies: 2
    Last Post: 01-02-2009, 04:09 AM
  5. Vector help
    By king_arthur in forum New To Java
    Replies: 3
    Last Post: 01-22-2008, 07:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •