Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Error handling with vectors

$
0
0
The program allows the user to input a string and add it to an vector. They can also type in a string and remove it from the vector. But I'm trying have it give an error message if the string to be removed is not in the vector. I think I just need to fix lines 61 and 62 but I'm not sure what to put.
import java.text.*;
import javax.swing.*;
import java.util.Vector;
import java.awt.*;
import java.awt.event.*;

public class vectprac extends JFrame implements ActionListener{
	
	private JButton addButton, deleteButton, printButton, closeButton;
	private JTextField input;
	private Vector<String> list;
	
	public static void main(String[] args){
		new vectprac();
	}
	
	public vectprac(){
		input = new JTextField(20);
		addButton = new JButton("Add");
		deleteButton = new JButton("Delete");
		printButton = new JButton("Print");
		closeButton = new JButton("Close");	
		list = new Vector<String>();
		
		this.pack();
		this.setSize(600, 80);
		this.setLocation(200, 200);
		this.setLayout(new FlowLayout());
		this.setTitle("Vector Practice");
		this.setVisible(true);			
		this.add(input);
		this.add(addButton);
		this.add(deleteButton);
		this.add(printButton);
		this.add(closeButton);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		addButton.addActionListener(this);	
		deleteButton.addActionListener(this);	
		printButton.addActionListener(this);	
		closeButton.addActionListener(this);
	}
			
	public void VectorOperations(){
		for(int i = 0; i < 12; i++){					
			String[] list = new String[12];
		}		
	}
		
	public void actionPerformed(ActionEvent ae){
		try{	
			String f = input.getText();
			if(ae.getSource() == addButton){
				list.add(f);	
			    JOptionPane.showMessageDialog(null, "Item Added");
				input.requestFocus();
				input.setText("");
			}	
			else if(ae.getSource() == deleteButton){
			    list.remove(f);
			    if(list.remove(f))
					JOptionPane.showMessageDialog(null, "Error: " + f + " not found");
				else
					JOptionPane.showMessageDialog(null, "Item Deleted");
				input.requestFocus();
				input.setText("");
				
			}
			else if(ae.getSource() == printButton){
				JOptionPane.showMessageDialog(this, list, "Vector Contents", JOptionPane.PLAIN_MESSAGE);
			} 
			else if(ae.getSource() == closeButton){
				shutDown();	
			}
		}	
		
		catch(Exception e){	
			JOptionPane.showMessageDialog(null, "Please enter a valid string");
		}
	}
	private void shutDown(){
		this.dispose();
	}
}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>