Q. Write a menu driven program to the following operations on a set of integers as shown in the following figure. The load operation should generate 10 random integers (2 digits) and display the numbers on the screen. The save operation should save the numbers to a file “numbers.txt”. The Sort menu provides various operations and the result is displayed on the screen.
Program
Program
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; public class Sort extends JFrame{ private JMenuBar mbMain; private JMenu mnuOperation,mnuSort; private JMenuItem miLoad,miSave,miExit,miAsc,miDesc; private JTextArea txtNumbers; private int nos[]=new int[10]; public Sort(){ mbMain = new JMenuBar(); mnuOperation = new JMenu("Operation"); mnuSort = new JMenu("Sort"); miLoad = new JMenuItem("Load"); miSave = new JMenuItem("Save"); miExit = new JMenuItem("Exit"); miAsc = new JMenuItem("Ascending"); miDesc = new JMenuItem("Descending"); txtNumbers = new JTextArea(); mbMain.add(mnuOperation); mbMain.add(mnuSort); mnuOperation.add(miLoad); mnuOperation.add(miSave); mnuOperation.addSeparator(); mnuOperation.add(miExit); mnuSort.add(miAsc); mnuSort.add(miDesc); setTitle("Sorting"); setSize(400,400); setLocation(100,100); add(new JScrollPane(txtNumbers)); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setJMenuBar(mbMain); miLoad.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ int n=10; txtNumbers.setText(""); for(int i=0;i<n;i++){ int t = (int)(Math.random()*100+1); if(t<10) t+=10; nos[i] = t; txtNumbers.append(nos[i]+"\n"); } } }); miExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0); } }); miSave.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ try{ BufferedWriter bw = new BufferedWriter( new FileWriter("numbers.txt")); for(int i=0;i<10;i++) bw.write(nos[i]+"\n"); bw.close(); } catch(Exception e){} } }); miAsc.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ int n=10; for(int i=0;i<n;i++){ for(int j=0;j<n-1-i;j++){ if(nos[j]>nos[j+1]){ int t = nos[j]; nos[j] = nos[j+1]; nos[j+1] = t; } } } txtNumbers.setText(""); for(int i=0;i<n;i++) txtNumbers.append(nos[i]+"\n"); } }); miDesc.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ int n=10; for(int i=0;i<n;i++){ for(int j=0;j<n-1-i;j++){ if(nos[j]<nos[j+1]){ int t = nos[j]; nos[j] = nos[j+1]; nos[j+1] = t; } } } txtNumbers.setText(""); for(int i=0;i<n;i++) txtNumbers.append(nos[i]+"\n"); } }); } public static void main(String args[]){ new Sort(); } }
0 Comments