class12 proggassign answers notes

66
Programming Assignments class 12 [email protected] Page 1 of 66 Create a Form to do the following: 1. Input a string in a text box and print its length in another text field. 2. Input a string and print it in reverse order in another text box. 3. Input a string and print a message whether it’s a palindrome string or not. A palindrome string is a string that reads same from start and end e.g. nitin 4. Input a string and print total number of vowels in it. Also count the total of individual vowels. 5. Input a string and convert it to uppercase and lowercase. 6. Input two strings in two text boxes and concat them and display the concated string in a third text box. 7. Input two strings in two text boxes and print whether they are same : a. Ignoring case b. Case sensitive 8. Input a string and print : a. First three characters b. Last two characters c. Two middle characters 9. Input a number and check whether it’s an even number or an odd number. 10. Input a number and print its table upto 10. 11. Input a number and reverse it and display it in another text box. 12. Input a number and count how many digits it contains. 13. Input a number and print sum of its individual digits. 14. Input a start value and an end value and display all the digits in between those two values. 15. Input a number and display whether it’s a prime number or not. 16. Input a number and display its sign i.e. positive, negative or zero. 17. Input a number and check whether it’s an armstrong number. Armstrong numbers are those three digit numbers whose sum of cube of individual digits is the number itself. 18. Input a number and print that number of prime numbers . 19. Create a button which when clicked will display all the armstrong numbers. 20. Input 3 numbers and print maximum of these three numbers. 21. Input a number and print its factorial. 22. The fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1,1. every subsequent value is the sum of the two values preceding it. Create a form that will display this series. 23. Compute the following series: a. 1+1/2+1/3+…..+1/n b. 1+1/2+1/2 2 +1/2 3 +…….+1/2 n 24. Input marks of 5 subjects and print its total, average and grade. Grade is based on the following rules: Average Grade >=90 S >=80 and <90 A >=70 and <80 B >=60 and <70 C >=50 and <60 D >=40 and <50 E <40 F 25. A bank pays 12% interest on a fixed deposit for 6 months or more. Input the deposited amount and the period for which the amount is deposited . Display the interest and total amount in two text boxes. 26. Input a number between 1-7 and display dayname as 1-Monday, 2- Tuesday….Also check for invalid value entered. 27. Input a number between 1-12 and display monthname as 1-January, 2- February….Also check for invalid value entered. 28. Input a number and print all the even numbers and odd numbers till that number. 29. Input a year and display if it is a leap year or not. 30. Write a program which will keep on asking for a number until user enters -999 and then will display the sum and count of those numbers. 31. Write a program to print the following series: 1 1 * 12 22 ** 123 333 *** 1234 4444 **** 12345 55555 *****

Upload: subhash-varghese

Post on 10-Apr-2015

142 views

Category:

Documents


0 download

DESCRIPTION

Programming assignments, answers and notes

TRANSCRIPT

Page 1: Class12 ProggAssign Answers Notes

Programming Assignments class 12 [email protected] Page 1 of 66 Create a Form to do the following: 1. Input a string in a text box and print its length in another text field. 2. Input a string and print it in reverse order in another text box. 3. Input a string and print a message whether it’s a palindrome string or not. A palindrome string is a string

that reads same from start and end e.g. nitin 4. Input a string and print total number of vowels in it. Also count the total of individual vowels. 5. Input a string and convert it to uppercase and lowercase. 6. Input two strings in two text boxes and concat them and display the concated string in a third text box. 7. Input two strings in two text boxes and print whether they are same :

a. Ignoring case b. Case sensitive

8. Input a string and print : a. First three characters b. Last two characters c. Two middle characters

9. Input a number and check whether it’s an even number or an odd number. 10. Input a number and print its table upto 10. 11. Input a number and reverse it and display it in another text box. 12. Input a number and count how many digits it contains. 13. Input a number and print sum of its individual digits. 14. Input a start value and an end value and display all the digits in between those two values. 15. Input a number and display whether it’s a prime number or not. 16. Input a number and display its sign i.e. positive, negative or zero. 17. Input a number and check whether it’s an armstrong number. Armstrong numbers are those three digit

numbers whose sum of cube of individual digits is the number itself. 18. Input a number and print that number of prime numbers . 19. Create a button which when clicked will display all the armstrong numbers. 20. Input 3 numbers and print maximum of these three numbers. 21. Input a number and print its factorial. 22. The fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1,1. every

subsequent value is the sum of the two values preceding it. Create a form that will display this series. 23. Compute the following series:

a. 1+1/2+1/3+…..+1/n b. 1+1/2+1/22+1/23+…….+1/2n

24. Input marks of 5 subjects and print its total, average and grade. Grade is based on the following rules: Average Grade >=90 S >=80 and <90 A >=70 and <80 B >=60 and <70 C >=50 and <60 D >=40 and <50 E <40 F

25. A bank pays 12% interest on a fixed deposit for 6 months or more. Input the deposited amount and the

period for which the amount is deposited . Display the interest and total amount in two text boxes. 26. Input a number between 1-7 and display dayname as 1-Monday, 2- Tuesday….Also check for invalid

value entered. 27. Input a number between 1-12 and display monthname as 1-January, 2- February….Also check for invalid

value entered. 28. Input a number and print all the even numbers and odd numbers till that number. 29. Input a year and display if it is a leap year or not. 30. Write a program which will keep on asking for a number until user enters -999 and then will display the

sum and count of those numbers. 31. Write a program to print the following series:

1 1 * 12 22 ** 123 333 *** 1234 4444 **** 12345 55555 *****

Page 2: Class12 ProggAssign Answers Notes

List Box class 12 [email protected] Page 2 of 66

1. LIST BOX: assuming that its name is jList1

a. To add items in a list box at design time do the following:

i. Select the List Box.

ii. From its Properties dialog box, click on the ellipsis next to ‘model.

iii. A model window will appear. There type the values you want to display in the

list box.

b. To add the values that you type in a text box into the List box or say to add the values

in the List Box at runtime do the following:

i. Select the List Box.

ii. From its Properties dialog box, click on the ellipsis next to ‘model.

iii. A model window will appear.

iv. Click on the drop down box displayed at the top of the model window and

select Custom code.

v. In the new window a text box will appear. There type the model name as

‘modLstCity. (It can be any name you want)

vi. Now click on the source tab.

vii. At the topmost line and just before the class definition begins add the line :

import javax.swing.*;

viii. At the bottom of the source window just above the ‘variable declaration code’

type the following :

1. DefaultListModel modLstCity=new DefaultListModel();

ix. Now on the button click event, type the following code:

1. modLstCity.addElement(txt1.getText());

c. To display the index number of the selected item in the list box do the following:

i. Select the List Box.

ii. From the shortcut menu select Events -> ListSelection > valueChanged and

type the following code there:

1. JOptionPane.showMessageDialog(null,jList1.getSelectedIndex());

d. To display the selected item in the list box in another text box do the following:

i. Select the List Box.

ii. From the shortcut menu select Events -> ListSelection _> valueChanged and

type the following code there:

1. txt2.setText(“”+jList1.getSelectedValue());

e. To search an entry in a list box do the following:

i. Add elements in a list box.

ii. Enter value to search in a text box namely txt.

String txt=jTextFieldTxt.getText();

int po=jList1.getNextMatch(txt,0,javax.swing.text.Position.Bias.Forward);

if (po==-1)

jLabelPosition.setText("Invalid entry");

else jLabelPosition.setText("Position : "+po);

Page 3: Class12 ProggAssign Answers Notes

List Box class 12 [email protected] Page 3 of 66

f. To delete an entry from the list box do the following:

i. Add elements in the list box.

ii. Create a button ‘Delete Item’ and add the following code:

modLstCity.removeElementAt(jList1.getSelectedIndex());

g. To copy a selected item of a list box to another list box on clicking a button:

i. Create a new list box. Name is jList2

ii. Create its model as described above as ‘modLstCity2’

iii. Add its DefaultListModel code in source window as explained above.

iv. Create a button ‘copy element’ and add the following code:

modLstCity2.addElement(jList1.getSelectedValue());

h. To insert an item before the selected item in a list box do the following:

i. Add elements in the list box.

ii. Create a button ‘Insert element’ and add the following code:

int pos=jList1.getSelectedIndex();

String s=txt1.getText();

modLstCity.insertElementAt(s, pos);

Page 4: Class12 ProggAssign Answers Notes

Combo Box class 12 [email protected] Page 4 of 66

2. Combo Boxes : assuming its name is jCombo1 a. To add items in a combo box at design time do the following:

i. Select the Combo Box.

ii. From its Properties dialog box, click on the ellipsis next to ‘model.

iii. A model window will appear. There type the values you want to display in the

combo box.

b. To add the values that you type in a text box into the Combo box or say to add the

values in the Combo Box at runtime do the following:

i. Select the Combo Box.

ii. From its Properties dialog box, click on the ellipsis next to ‘model.

iii. A model window will appear.

iv. Click on the drop down box displayed at the top of the model window and

select Custom code.

v. In the new window a text box will appear. There type the model name as

‘modCmbState. (It can be any name you want)

vi. Now click on the source tab.

vii. At the topmost line and just before the class definition begins add the line :

import javax.swing.*;

viii. At the bottom of the source window just above the ‘variable declaration code’

type the following :

1. DefaultComboBoxModel modCmbState=new DefaultComboBoxModel();

ix. Add a button ‘Add’ and type the following code :

1. modCmbState.addElement(txt1.getText());

c. To display the index number of the selected item in the combo box do the following:

i. Add items in the Combo Box.

ii. Select the Combo Box.

iii. From the shortcut menu select Events -> Items > itemStateChanged and type

the following code there:

1. JOptionPane.showMessageDialog(null,jCombo1.getSelectedIndex());

d. To display the selected item in the combo box in another text box do the following:

i. Select the Combo Box.

ii. From the shortcut menu select Events -> Items > itemStateChanged and type

the following code there:

1. txt2.setText(""+jCombo1.getSelectedItem());

e. To search an entry in a combo box do the following:

i. Add elements in a combo box.

ii. Enter value to search in a text box namely txt2.

iii. Create a button ‘Search’ and add the following piece of code in it:

Page 5: Class12 ProggAssign Answers Notes

Combo Box class 12 [email protected] Page 5 of 66

String s=txt2.getText();

jCombo1.setSelectedItem(s);

f. To delete an entry from the combo box do the following:

i. Add elements in the combo box.

ii. Create a button ‘Delete Item’ and add the following code:

modCmbState.removeElementAt(jCombo1.getSelectedIndex());

g. To copy a selected item of a combo box to another combo box on clicking a button:

i. Create a new combo box. Name is jCombo2

ii. Create its model as described above as ‘modCmbState2’

iii. Add its DefaultComboModel code in source window as explained above.

iv. Create a button ‘copy element’ and add the following code:

modCmbState2.addElement(jCombo1.getSelectedItem());

h. To insert an item before the selected item in a combo box do the following:

i. Add elements in the combo box.

ii. Create a button ‘Insert element’ and add the following code:

int pos=jCombo1.getSelectedIndex();

String s=txt1.getText();

modCmbState.insertElementAt(s, pos);

Page 6: Class12 ProggAssign Answers Notes

Check Box class 12 [email protected] Page 6 of 66

Check Boxes : it returns only two values; true or false i.e. selected or not selected.

1. To add a group of check box do the following:

a. From the palette add 3 checkboxes on to the form

b. To change their names, select it and from the shortcut menu select ‘change variable

name’ and give a name ex. chkInf, chkPhy and chkBio for our program.

c. To change their displayed text, select it and from the shortcut menu select ‘Edit Text’

and give a name ex. Informatics, Physics and Biology for our program.

2. To display value of the check box which can be either true or false or say selected or not

selected do the following:

a. Select the check box ‘chkInf’

b. From the shortcut menu, select Events -> Action -> actionPerformed and add the

following code:

boolean s=chkInf.isSelected();

String caption=chkInf.getText();

txt1.setText(caption + " is "+ s);

c. Do (a) and (b) steps for other two check boxes namely chkPhy and chkBio and in the

code just change chkInf to chkPhy and chkBio respectively.

3. To display all the options of check boxes which are selected in a textarea namely ‘ta’ on click

of a button , add the following code to the button:

ta.setText("The options Selected: \n");

if(chkInf.isSelected()==true)

ta.append(chkInf.getText() + " ");

if(chkPhy.isSelected()==true)

ta.append(chkPhy.getText()+" ");

if(chkBio.isSelected()==true)

ta.append(chkBio.getText()+" ");

4. To set all the check boxes value to false or unselect them all, do the following:

a. Add a button titled ‘Unselect All’

b. Add the following code to the

button:

chkInf.setSelected(false);

chkPhy.setSelected(false);

chkBio.setSelected(false);

txt1.setText("");

c.

On Clicking Unselect All button

Page 7: Class12 ProggAssign Answers Notes

Radio Buttons class 12 [email protected] Page 7 of 66

Radio Buttons/Option Buttons: In radiobutton we can have the only one decision. But checkbox we can have mulitiple options. Based on the usage we choose these controls. for example, RadioButton ----------- Gender - ⃝ Male ⃝ Female here we can select only one option

CheckBox -------- your Interested Games? ⃞ cricket ⃞ football ⃞ valleyball ⃞ hockey here you may have more than option.

1. To add a group of radio buttons to ask for stream selected, Science, Commerce or Arts.

a. Add three radio buttons on to the form.

b. Change their names to opSc, opCom and opArts, by selecting ‘Change Variable

Name’ option from the shortcut menu.

c. Change their displayed text to Science, Commerce and Arts by selecting ‘Edit Text’

option from the shortcut menu.

d. Now to have only one radio button selected out of these three do the following:

i. From the palette drag component namely ‘Button Group’ on the form. This

component will not be visible on the form but it will be visible in the inspector

window under ‘Other Components’ heading’. The default name will be

‘buttonGroup1’. Select this name , and from the shortcut menu select ‘Change

variable name’ option and change the name to grStream.

ii. Now in the form, select all the three buttons together and open Properties

dialog box from the shortcut menu.

iii. Click the drop down next to buttonGroup option and select grStream from the

dropdown and close the window.

iv. You will see that all the three buttons are now

connected together

v. These steps will ensure that only one of these

radio buttons is selected or you can say that

these three buttons belong to a group namely ‘grStream’.

2. To display value of the radio button which can be either true or false or say selected or not

selected do the following:

a. Select the radio button ‘opSc’

b. From the shortcut menu, select Events -> Action -> actionPerformed and add the

following code:

boolean s=opSc.isSelected();

String caption=opSc.getText();

txt1.setText(caption + " is "+ s);

c. Do (a) and (b) steps for other two radio buttons namely opCom and opArts and in the

code just change opSc to opCom and opArts respectively.

3. To set all the radio buttons to false or unselected state, do the following:

a. Add a button with title “Unselect”.

b. Add the code : grStream.clearSelection(); // name of the buttonGroup

Page 8: Class12 ProggAssign Answers Notes

Radio Buttons class 12 [email protected] Page 8 of 66

4. Now, add three ‘Panel’ container on the form. Add a border around each panel. Name them

as panSc, panCom and panArts and add different labels in each panel as shown below:

5. Now open the source window and

add the following code just below the

initComponents(); line. These line of

codes set there visible property to

false when the form loads:-

initComponents();

panSc.setVisible(false);

panCom.setVisible(false);

panArts.setVisible(false);

6. Next step is, when we click ‘opSc’ option button, ‘panSc’ should be visible and when we click

‘opCom’ option button, ‘panCom’ should be visible and when we click ‘opArts’ option button,

‘panArts’ should be visible.

7. Select ‘opSc’ button and from the shortcut menu select Events -> Action -> actionPerformed

and add the following code:

panSc.setVisible(true);

panCom.setVisible(false);

panArts.setVisible(false);

8. Select ‘opCom’ button and from the shortcut menu select Events -> Action ->

actionPerformed and add the following code:

panSc.setVisible(false);

panCom.setVisible(true);

panArts.setVisible(false);

9. Select ‘opArts’ button and from the shortcut menu select Events -> Action ->

actionPerformed and add the following code:

panSc.setVisible(false);

panCom.setVisible(false);

panArts.setVisible(true);

10.

Page 9: Class12 ProggAssign Answers Notes

Classes & Objects class 12 [email protected] Page 9 of 66 Class : this is a template from which you can create objects. The definition of class includes the formal specifications for the class and any data and method in it. Object: this is an instance of a class much as a variable is an instance of a data type. We can think of a class as the type of an object. Objects encapsulates methods and instance variables. Data members: those variables that are part of a class. We use them to store the data the object uses. Objects supports both ‘instance variables’ whose values are specific to the object and ‘class/static variables’ whose values are shared among the objects of a specified class. Methods/Functions: this is a function built into a class or object. We have instance and class methods. We can use instance methods with objects and class methods just by referring to the class name, no object is required. Class declaration and definition syntax: [access] class class_name [extends …] [implements…] { // class definition [access] [static] type variable1; [access] [static] type variable2; . . . [access] [static] type variableN; [access] [static] return-type method1([parameter-list]) { (method definition) ….. }

[access] [static] return-type method2([parameter-list]) { (method definition) ….. } . . . [access] [static] return-type methodN([parameter-list]) { (method definition) ….. } } // end class definition The keyword ‘static’ turns variable into a class variable and a methods into a class method. The ‘access’ term specifies the accessibility of the class or a class method or a class variable to bthe rest of the program and it can be public, private or protected. Instance and Class variables: instance variables are specific to the objects. If you have 2 objects(i.e. two instances of a class), the instance variables in each object are independent of the instance variables in other object On the other hand, class variables of both the objects will refer to the same data and therefore will hgold the same value. Ex. Create a class named ‘A’ by

Page 10: Class12 ProggAssign Answers Notes

Classes & Objects class 12 [email protected] Page 10 of 66 public class A { int a; // instance variable static int b; //class variable public void printmsg(){ // an instance method S.o.p(“Hello my friend…….”); } public static void printmsg2() { // a static method S.o.p(“Hello World…..”); } …… } // end class A Now create a jFrame form and add a button in the form. Add the following code behind the button. A a1=new A(); // object a1 of class A A a2=new A(); // object a2 of class A a1.a=10; // a1 accessing instance variable a S.o.p(“Value of a1.a=” + a1.a); S.o.p(“Value of a2.a=” + a2.a); a1.b=100; // a1 accessing class variable b S.o.p(“Value of a1.b=” + a1.b); S.o.p(“Value of a2.b=” + a2.b); Internally what happens is that : Object a1 Object a2 Static variable In the above example, instance variable ‘a’ is different for both the objects. Thus changes made to ‘a’ by the object a1 is not reflected in object a2. In the above example, the class variable ‘b’ is same for both the objects or say both the objects share the same class variable ‘b’. thus changes made to ‘b’ by object a1 is reflected in object a2. To declare and define a method, you can:

Use access specifier Specify the return type of the method if you want to return a value(such as int, float,an object type or void

if the method doesn’t return anything. Give the method’s name and Place the list of the parameters you intend to pass to the method.

About variables:

An instance variable can be accessed ONLY by an instance of a class. An instance variable is different for each instance of a class. A static variable is shared between instances of a class. It can be used by a class also i.e. A.a=200 is valid.

About Methods:

An instance method can ONLY be accessed by an instance of a class. It cannot be accessed by the class directly.

A static method can be accessed by an instance of a class as well as the class itself. a1.printmsg(); // object a1 calling instance method a2.printmsg(); // object a2 calling instance method A.printmsg2(); // class A invoking static method A.printmsg(); // illegal as class can’t invoke instance method directly a1.printmsg2(); // instance of a class can access static method also

Output: Value of a1.a=10 Value of a2.a=0 Value of a1.b=100 Value of a2.b=100

ba a

Page 11: Class12 ProggAssign Answers Notes

MyMath class XII [email protected] Page 11 of 66 *** A user defined class ‘MyMath’ with various mathematical functions created by the user. Note that all functions are declared to be static and thus they can be directly qualified with the class name i.e. you can call fact function as MyMath.fact(23) public class MyMath { static int fact(int n){ int f=1; for(int i=1;i<=n;i++) f=f*i; return f; } static int findmax(int a,int b, int c){ int max; if(a>b && a>c) max=a; else if(b>a && b>c) max=b; else max=c; return max; } static int countdigits(long n){ int c=0; while(n>0){ c=c+1; n=n/10; } return c; } static long reversedigits(long n){ int c=0; long temp=0; while(n>0){ temp=(temp*10)+(n%10); n=n/10; } return temp; } static long adddigits(long n){ long sum=0; while(n>0){ sum=sum+(n%10); n=n/10; } return sum; } static long cubedigit(long n){ return n * n * n ; } static long sumofcube(long n){ long sum=0; while(n>0){ long i=n%10; sum=sum+cubedigit(i); n/=10; } return sum; }

Page 12: Class12 ProggAssign Answers Notes

MyMath class XII [email protected] Page 12 of 66 private static boolean isprime(long n){ boolean tf=true; for(long i=2;i<=n/2;i++){ if(n%i==0){ tf=false; break; } } return tf; } static boolean evenodd(int n){ if(n%2==0) return true; else return false; } static String sign(long n){ if(n<0) return "Negative"; else if (n>0) return "Positive"; else return "Zero"; } } // end class

Page 13: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 13 of 66

1. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); int n=s.length(); t2.setText("The Length : " + n); }

2.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); int n=s.length(); String nws=""; for(int i=n-1;i>=0;--i){ nws=nws+s.charAt(i); } t2.setText("Reverse : " + nws); }

3.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); boolean yn=palin(s); t2.setText("Palindrome : " + yn); }

boolean palin(String s){ int n=s.length(); String nws=""; for(int i=n-1;i>=0;--i){ nws=nws+s.charAt(i); } if(s.equalsIgnoreCase(nws)==true) return true; else return false; }

Page 14: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 14 of 66

4.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); s=s.toUpperCase(); int vow=0; int a=0;int e=0; int i=0; int o=0; int u=0; int c=0; while(c<s.length()){ if(isVowel(s.charAt(c))==true){ ++vow; a=s.charAt(c)=='A'?++a:a; e=s.charAt(c)=='E'?++e:e; i=s.charAt(c)=='I'?++i:i; o=s.charAt(c)=='O'?++o:o; u=s.charAt(c)=='U'?++u:u; } c++; } ta.append("Total Vowels : "+ vow + "\n"); ta.append("Total 'a' : " + a + "\n"); ta.append("Total 'e' : " + e + "\n"); ta.append("Total 'i' : " + i + "\n"); ta.append("Total 'o' : " + o + "\n"); ta.append("Total 'u' : " + u + "\n"); } boolean isVowel(char c){ if (c=='A'||c=='E'||c=='I'||c=='O'||c=='U') return true; else return false; }

5.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); s=s.toUpperCase(); t2.setText(s); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); s=s.toLowerCase(); t2.setText(s); }

Page 15: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 15 of 66

6.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); s1=s1.toUpperCase(); String s2=t2.getText(); s2=s2.toUpperCase(); String s3=s1.concat(" "+s2); t3.setText("Hello " + s3); }

7.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); String s2=t2.getText(); boolean same; if(s1.equals(""+s2)) same=true; else same=false; t3.setText("Similar " + same); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); String s2=t2.getText(); boolean same; if(s1.equalsIgnoreCase(s2)) same=true; else same=false; t3.setText("Similar " + same); }

Page 16: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 16 of 66

8. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String str=t1.getText(); int s=Integer.parseInt(t2.getText()); int e=Integer.parseInt(t3.getText()); String str2=str.substring(s,e); t4.setText(str2); }

The following forms assumes that you have created ‘MyMath’ class as was told. These forms will use the static methods defined in MyMath class.

9.

private void btnEvenActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); int n=Integer.parseInt(s); if(MyMath.evenodd(n)) s="It's an Even Number"; else s="It's an Odd Number"; res.setText(s); }

10.

private void btnTableActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); int n=0; try{ n=Integer.parseInt(s); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } for(int i=1;i<=10;i++){ s=""+n +" x " + i + " = "+ n*i; ta.append(s + "\n"); } }

Page 17: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 17 of 66

11. private void btnReverseActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); long n=0; try{ n=Long.parseLong(s); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } n=MyMath.reversedigits(n); t2.setText("Reverse is : " + n); }

12. private void btnCountDigitsActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); long n=0; try{ n=Long.parseLong(s); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } n=MyMath.countdigits(n); t2.setText("Total Digits : " + n); } 13. private void btnSumDigitsActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); long n=0; try{ n=Long.parseLong(s); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } n=MyMath.adddigits(n); t2.setText("Sum of Digits : " + n); }

14. private void btnPrntSeriesActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); String s2=t2.getText(); long n1=0;long n2=0; try{ n1=Long.parseLong(s1); n2=Long.parseLong(s2); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } if(n1>n2){ long t=n1; n1=n2; n2=t; } s1="";

Page 18: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 18 of 66 for (long i=n1;i<=n2;i++) s1=s1+i+" "; lbl1.setText(s1); }

15.

private void btnPrimeActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); long n1=0; try{ n1=Long.parseLong(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } if(MyMath.isprime(n1)) s1="The Number is Prime"; else s1="The Number is Not Prime"; lbl1.setText(s1); }

16.

private void btnPosNegActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); long n1=0; try{ n1=Long.parseLong(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } s1="The Number is a : " + MyMath.sign(n1) +" Number"; lbl1.setText(s1); }

Page 19: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 19 of 66

17. private void btnArmstrongActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); long n1=0; long sum=0; try{ n1=Long.parseLong(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } long temp=n1; while(temp>0){ long n=temp%10; sum=MyMath.cubedigit(n)+sum; temp/=10; } System.out.print(""+sum); if(n1==sum) lbl1.setText("An Armstrong Number"); else lbl1.setText("Not an Armstrong Number"); } 18. private void btnPrimesActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); long n1=0; try{ n1=Long.parseLong(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } long i,j; for(i=1,j=1; j<=n1;++i){ if(MyMath.isprime(i)==true){ ta.append(""+i +"\n"); ++j; } } } 19. private void btnArmstrongActionPerformed(java.awt.event.ActionEvent evt) { for(long n=100;n<=999;++n){ if(n==MyMath.sumofcube(n)){ ta.append(""+n+"\n"); } } }

Page 20: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 20 of 66 20. private void btnMaxActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); String s2=t2.getText(); String s3=t3.getText(); int n1=0;int n2=0;int n3=0; try{ n1=Integer.parseInt(s1); n2=Integer.parseInt(s2); n3=Integer.parseInt(s3); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } int max=MyMath.findmax(n1, n2, n3); t4.setText("The Maximum Vaslue is : "+ max); } 21. private void btnFactActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); int n1=0; try{ n1=Integer.parseInt(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } int fact=MyMath.fact(n1); t4.setText("The Factorial : "+ fact); } 22. private void btnFibbActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); int n=0;int n1=0; int n2=0;int n3=0; try{ n=Integer.parseInt(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } n1=0; n2=1; String s=""+n1 +" "+ n2 +" "; for(int i=1;i<=n-2;++i){ n3=n1+n2; s=s+n3+" "; n1=n2; n2=n3; } t4.setText(s); }

Page 21: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 21 of 66 23. private void btnFibbActionPerformed(java.awt.event.ActionEvent evt) { String s1=t1.getText(); float sum=1; float n=0; try{ n=Float.parseFloat(s1); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid Integer Value"); t1.requestFocus(); return; } for(float i=2;i<=n;i++){ sum=sum+1/i; } t4.setText("The sum is : "+sum); }

24. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int e,p,c,m,i; int t; double per; String gr; e=Integer.parseInt(t1.getText()); p=Integer.parseInt(t2.getText()); c=Integer.parseInt(t3.getText()); m=Integer.parseInt(t4.getText()); i=Integer.parseInt(t5.getText()); t=e+p+c+m+i; per=t/500.0 * 100; gr=grade(per); t6.setText(""+t); t7.setText(""+per +"%"); t8.setText(""+gr); } String grade(double p){ String g=""; if(p>=90) g="S"; else if(p>=80) g="A"; else if(p>=70) g="B"; else if(p>=60) g="C"; else if(p>=50) g="D"; else if(p>=40) g="E"; else g="Fail"; return g; } 25. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

Page 22: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 22 of 66 long dep=Long.parseLong(t1.getText()); int time=Integer.parseInt(t2.getText()); double intamt=0.0; double tamt=0; t3.setEditable(false); t4.setEditable(false); if(time>6){ intamt=dep*(12.0/100); } tamt=dep+intamt; t3.setText(""+intamt); t4.setText(""+tamt); }

26. private void btnDaynameActionPerformed(java.awt.event.ActionEvent evt) { int d=0; String day=""; try{ d=Integer.parseInt(t1.getText()); }catch(Exception e){ JOptionPane.showMessageDialog(this,"Enter a Valid value.."); t1.requestFocus(); return; } if(d<1||d>7){ JOptionPane.showMessageDialog(this,"Enter value between 1-7"); t1.requestFocus(); return; } switch(d){ case 1:day="Monday";break; case 2:day="Tuesday";break; case 3:day="Wednesday";break; case 4:day="Thursday";break; case 5:day="Friday";break; case 6:day="Saturday";break; case 7:day="Sunday";break; } t2.setText("It is "+day); } 27. Do Yourself…..Same as 26

Page 23: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 23 of 66 28. private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int n=Integer.parseInt(t1.getText()); int nums=1; String odd=" "; String even=" "; for (int i=1;i<=n*2;++i){ if(nums%2==0) even=even+nums+" "; else odd=odd+nums+" "; ++nums; } lblEven.setText(even); lblOdd.setText(odd); } 29. do it yourself …….

30.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int n; int sum=0; int count=0; while (true){ String s=JOptionPane.showInputDialog("Enter a Number : (-999 to STOP ) "); n=Integer.parseInt(s); if(n==-999){ break; } else{ ta.append(s + "\n"); sum=sum+n; ++count; } } JOptionPane.showMessageDialog(this, "Total Numbers :"+count + " Sum = "+ sum); }

Page 24: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 24 of 66 31. Enter a sentence in a text box and apply title case on it i.e. first letter of every word should be

capitalized.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); String nws=""; String s2=""; boolean flag=false; char c; int l=s.length(); int i=0; s2=""+s.charAt(0); s2=s2.toUpperCase(); nws=nws+s2; ++i; while(i<=l-1){ while(true){ c=s.charAt(i); if(c==32){ ++i; flag=true; nws=nws+c; continue; }else{ s2=""+s.charAt(i); break; } } // end inner while if(flag){ s2=s2.toUpperCase(); flag=false; } nws=nws+s2; ++i; } // end outer while t2.setText(nws); }

Page 25: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 25 of 66 32. Type a text in a text box and apply Toggle case on it i.e. uppercase should be converted to

lowercase and vice versa.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); String nws=""; int n; int l=s.length(); int i=0; while(i<=l-1){ char c=s.charAt(i); n=c; if(c>=97 && c<=122){ n=n-32; c=(char)n; } else if(c>=65 && c<=90){ n=n+32; c=(char)n; } nws=nws+c; ++i; }// end while t2.setText(nws); } Replace a word with another word as show below:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String str=t3.getText(); String search=t1.getText(); String repl=t2.getText(); String nws=""; nws=str.replaceAll(search, repl); t3.setText(nws); }

Now convert him with her AND his with her yourself

Page 26: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 26 of 66

33. The following GUI program illustrates various ‘Color’ concepts. Before creating this form , do the following:

write the code at the topmost line : import java.awt.Color ; add a listbox and name it ‘lstColor’ and in model property type : RED, GREEN, BLUE, BLACK and

YELLOW. add a combbox and name it ‘cmbColor’ and in model property type : RED, GREEN, BLUE, PINK and

ORANGE. Add 4 radio buttons and name them opRed, opGreen, opBlue and OPBlack and change their text

properties to RED. GREEN, BLUE and BLACK respectively. Assign the ButtonGroup property of these buttons as ‘buttonGroup1’

Add a label and name it as ‘lbl1’. Also ‘check’ its ‘Opaque’ property to true.

private void lstColorValueChanged(javax.swing.event.ListSelectionEvent evt) { String s=""+lstColor.getSelectedValue(); int i=lstColor.getSelectedIndex(); Color c= Color.white; if(i==0) c=Color.RED; if(i==1) c=Color.GREEN; if(i==2) c=Color.BLUE; if(i==3) c=Color.BLACK; if(i==4) c=Color.YELLOW; lbl1.setText(s); lbl1.setBackground(c); }

private void cmbColorItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+cmbColor.getSelectedItem(); int i=cmbColor.getSelectedIndex(); Color c= Color.white; if(i==0) c=Color.RED; if(i==1) c=Color.GREEN; if(i==2) c=Color.BLUE; if(i==3) c=Color.PINK; if(i==4) c=Color.ORANGE; lbl1.setText(s); lbl1.setBackground(c); } private void opRedItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opRed.getText(); Color c= Color.red; lbl1.setText(s); lbl1.setBackground(c); }

Page 27: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 27 of 66 private void opGreenItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opGreen.getText(); Color c= Color.green; lbl1.setText(s); lbl1.setBackground(c); } private void opBlueItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opBlue.getText(); Color c= Color.blue; lbl1.setText(s); lbl1.setBackground(c); } private void opBlackItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opBlack.getText(); Color c= Color.black; lbl1.setText(s); lbl1.setBackground(c); }

34. The following GUI program illustrates ‘Font’ concepts: At the topmost line add the code : import java.awt.Font; Add a list box and name it ‘lstFont’ and type the following fonts in its model property. Add a combo box and name it ‘cmbSize’ and type various sizes 8,10,12…..28. Add three check boxes and name them chkBold, chkItalic and chkPlain and set the text properties for

them respectively as shown below

Page 28: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 28 of 66

private void btnSETActionPerformed(java.awt.event.ActionEvent evt) { String fontname=""+lstFont.getSelectedValue(); String fontstyle=""; Int fontsize=Integer.parseInt(""+cmbSize.getSelectedItem()); if(chkBold.isSelected()) txt1.setFont(new Font(fontname,Font.BOLD,fontsize)); if(chkItalic.isSelected()) txt1.setFont(new Font(fontname,Font.ITALIC,fontsize)); if(chkPlain.isSelected()) txt1.setFont(new Font(fontname,Font.PLAIN,fontsize)); }

Page 29: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 29 of 66

Before cut and copy

After CUT

After PASTE

After COPY

After PASTE private void btnCutActionPerformed(java.awt.event.ActionEvent evt) { txt1.cut(); } private void btnCopyActionPerformed(java.awt.event.ActionEvent evt) { txt1.copy(); } private void btnPasteActionPerformed(java.awt.event.ActionEvent evt) { txt1.paste(); }

Page 30: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 30 of 66 35. Enter a sentence in a text box and apply title case on it i.e. first letter of every word should be

capitalized.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); String nws=""; String s2=""; boolean flag=false; char c; int l=s.length(); int i=0; s2=""+s.charAt(0); s2=s2.toUpperCase(); nws=nws+s2; ++i; while(i<=l-1){ while(true){ c=s.charAt(i); if(c==32){ ++i; flag=true; nws=nws+c; continue; }else{ s2=""+s.charAt(i); break; } } // end inner while if(flag){ s2=s2.toUpperCase(); flag=false; } nws=nws+s2; ++i; } // end outer while t2.setText(nws); }

Page 31: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 31 of 66 36. Type a text in a text box and apply Toggle case on it i.e. uppercase should be converted to

lowercase and vice versa.

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { String s=t1.getText(); String nws=""; int n; int l=s.length(); int i=0; while(i<=l-1){ char c=s.charAt(i); n=c; if(c>=97 && c<=122){ n=n-32; c=(char)n; } else if(c>=65 && c<=90){ n=n+32; c=(char)n; } nws=nws+c; ++i; }// end while t2.setText(nws); } Replace a word with another word as show below:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String str=t3.getText(); String search=t1.getText(); String repl=t2.getText(); String nws=""; nws=str.replaceAll(search, repl); t3.setText(nws); }

Now convert him with her AND his with her yourself

Page 32: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 32 of 66

37. The following GUI program illustrates various ‘Color’ concepts. Before creating this form , do the following:

write the code at the topmost line : import java.awt.Color ; add a listbox and name it ‘lstColor’ and in model property type : RED, GREEN, BLUE, BLACK and

YELLOW. add a combbox and name it ‘cmbColor’ and in model property type : RED, GREEN, BLUE, PINK and

ORANGE. Add 4 radio buttons and name them opRed, opGreen, opBlue and OPBlack and change their text

properties to RED. GREEN, BLUE and BLACK respectively. Assign the ButtonGroup property of these buttons as ‘buttonGroup1’

Add a label and name it as ‘lbl1’. Also ‘check’ its ‘Opaque’ property to true.

private void lstColorValueChanged(javax.swing.event.ListSelectionEvent evt) { String s=""+lstColor.getSelectedValue(); int i=lstColor.getSelectedIndex(); Color c= Color.white; if(i==0) c=Color.RED; if(i==1) c=Color.GREEN; if(i==2) c=Color.BLUE; if(i==3) c=Color.BLACK; if(i==4) c=Color.YELLOW; lbl1.setText(s); lbl1.setBackground(c); }

private void cmbColorItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+cmbColor.getSelectedItem(); int i=cmbColor.getSelectedIndex(); Color c= Color.white; if(i==0) c=Color.RED; if(i==1) c=Color.GREEN; if(i==2) c=Color.BLUE; if(i==3) c=Color.PINK; if(i==4) c=Color.ORANGE; lbl1.setText(s); lbl1.setBackground(c); } private void opRedItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opRed.getText(); Color c= Color.red; lbl1.setText(s); lbl1.setBackground(c); }

Page 33: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 33 of 66 private void opGreenItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opGreen.getText(); Color c= Color.green; lbl1.setText(s); lbl1.setBackground(c); } private void opBlueItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opBlue.getText(); Color c= Color.blue; lbl1.setText(s); lbl1.setBackground(c); } private void opBlackItemStateChanged(java.awt.event.ItemEvent evt) { String s=""+opBlack.getText(); Color c= Color.black; lbl1.setText(s); lbl1.setBackground(c); }

38. The following GUI program illustrates ‘Font’ concepts: At the topmost line add the code : import java.awt.Font; Add a list box and name it ‘lstFont’ and type the following fonts in its model property. Add a combo box and name it ‘cmbSize’ and type various sizes 8,10,12…..28. Add three check boxes and name them chkBold, chkItalic and chkPlain and set the text properties for

them respectively as shown below

Page 34: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 34 of 66

private void btnSETActionPerformed(java.awt.event.ActionEvent evt) { String fontname=""+lstFont.getSelectedValue(); String fontstyle=""; Int fontsize=Integer.parseInt(""+cmbSize.getSelectedItem()); if(chkBold.isSelected()) txt1.setFont(new Font(fontname,Font.BOLD,fontsize)); if(chkItalic.isSelected()) txt1.setFont(new Font(fontname,Font.ITALIC,fontsize)); if(chkPlain.isSelected()) txt1.setFont(new Font(fontname,Font.PLAIN,fontsize)); }

Page 35: Class12 ProggAssign Answers Notes

Assignment Answers class XII [email protected] Page 35 of 66

Before cut and copy

After CUT

After PASTE

After COPY

After PASTE private void btnCutActionPerformed(java.awt.event.ActionEvent evt) { txt1.cut(); } private void btnCopyActionPerformed(java.awt.event.ActionEvent evt) { txt1.copy(); } private void btnPasteActionPerformed(java.awt.event.ActionEvent evt) { txt1.paste(); }

Page 36: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 36 of 66

Data Table

Add a jTable control on to the form. Create its model the same way you created for ListBox and ComboBox. Select jTable -> Properties -> model -> Custom Code -> type the name of the model as ‘modTable’ In the source window in the last line, just above variable declarations code add the following:

o DefaultTableModel modTable=new DefaultTableModel(); o Vector rows=new Vector();

Add the following lines of code in source window: o import java.util.*; //line to add o Import javax.swing.*; //line to add o import javax.swing.table.*; //line to add

o public class swingTable extends javax.swing.JFrame { /** Creates new form swingTable */ public swingTable() { initComponents(); modTable.addColumn("Roll #"); //line to add modTable.addColumn("Reg #"); //line to add modTable.addColumn("Name"); //line to add modTable.addColumn("Class"); //line to add modTable.addColumn("Section"); //line to add modTable.addColumn("Gender"); //line to add modTable2.addColumn("Fields"); //line to add modTable2.addColumn("Values"); //line to add }

Page 37: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 37 of 66

Coding behind ‘Add Record’ button private void btnAddRecActionPerformed(java.awt.event.ActionEvent evt) { Vector row1=new Vector(); row1.addElement(txt1.getText()); row1.addElement(txt2.getText()); row1.addElement(txt3.getText()); row1.addElement(cmbClass.getSelectedItem()); row1.addElement(cmbSection.getSelectedItem()); if(opMale.isSelected()==true) row1.addElement(opMale.getText()); else row1.addElement(opFemale.getText()); modTable.addRow(row1); btnClear.doClick(); txt1.requestFocus(); } Coding behind ‘Remove’ button private void btnRemoveRecActionPerformed(java.awt.event.ActionEvent evt) { modTable.removeRow(jTable1.getSelectedRow()); }

Page 38: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 38 of 66 Coding behind ‘Get Values’ button

private void btnGetValuesActionPerformed(java.awt.event.ActionEvent evt) { String gender=""; int n; n=jTable1.getSelectedRow(); JOptionPane.showMessageDialog(this, n); txt1.setText(""+modTable.getValueAt(n, 0)); txt2.setText(""+modTable.getValueAt(n, 1)); txt3.setText(""+modTable.getValueAt(n, 2)); cmbClass.setSelectedItem(""+modTable.getValueAt(n, 3)); cmbSection.setSelectedItem(""+modTable.getValueAt(n, 4)); gender=""+modTable.getValueAt(n, 5); if(gender.equalsIgnoreCase("MALE")) opMale.setSelected(true); else opFemale.setSelected(true); }

Page 39: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 39 of 66

Coding behind ‘Count Records ClassWise’ button. This coding assumes that you enter class in a sorted order.

private void btnCountRecClassWiseActionPerformed(java.awt.event.ActionEvent evt) { int t=jTable1.getRowCount(); int c=0; int countclass=0; String res=""; while(c<=t-1){ String cl=""+modTable.getValueAt(c, 3); while(cl.equals(""+modTable.getValueAt(c, 3))){ ++countclass; ++c; if(c>t-1)break; if(!(cl.equals(""+modTable.getValueAt(c, 3)))){ res=res+"Class: "+cl+" Total: "+countclass+"\n"; countclass=0; break; }//end if }//end inner while if(c>t-1){ res=res+"Class: "+cl+" Total: "+countclass+"\n"; break; } Coding behind ‘Count Records’ button private void btnCountRecsActionPerformed(java.awt.event.ActionEvent evt) { int c=jTable1.getRowCount(); JOptionPane.showMessageDialog(this, c); }

Page 40: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 40 of 66 Coding behind ‘Clear Values’ button. private void btnClearActionPerformed(java.awt.event.ActionEvent evt) { txt1.setText(""); txt2.setText(""); txt3.setText(""); buttonGroup1.clearSelection(); } Coding behind JTable1 -> Events -> Mouse -> mouseClicked private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { btnGetValues.doClick(); } Coding behind ‘Copy Selection’ button

private void btnCopySelectionActionPerformed(java.awt.event.ActionEvent evt) { int n=jTable1.getSelectedRow(); int i=0; while(modTable2.getRowCount()>0) modTable2.removeRow(i); for(i=0;i<=5;i++){ Vector row=new Vector(); String colname=modTable.getColumnName(i); String colvalue=""+modTable.getValueAt(n, i); row.addElement(colname); row.addElement(colvalue); modTable2.addRow(row); } // end for }

Page 41: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 41 of 66 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author subhashv */ import java.sql.*; public class ConnectSv { public static Connection connect() throws Exception{ String url="jdbc:mysql://localhost/xav"; String uname="root"; String pass="shibu24"; Class.forName("com.mysql.jdbc.Driver").newInstance(); return DriverManager.getConnection(url, uname, pass); } }

Page 42: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 42 of 66 Code behind ‘Insert Record’ button.

Code in NEXT Page

Page 43: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 43 of 66 private void btnInsertRec1ActionPerformed(java.awt.event.ActionEvent evt) { int r=jTable1.getSelectedRow(); Vector row1=new Vector(); row1.addElement(txt1.getText()); row1.addElement(txt2.getText()); row1.addElement(txt3.getText()); row1.addElement(cmbClass.getSelectedItem()); row1.addElement(cmbSection.getSelectedItem()); if(opMale.isSelected()==true) row1.addElement(opMale.getText()); else row1.addElement(opFemale.getText()); modTable.insertRow(r, row1); btnClear.doClick(); txt1.requestFocus(); } Code behind ‘Update Record’ button:

Before Update

Page 44: Class12 ProggAssign Answers Notes

Data Table class XII [email protected] Page 44 of 66

After UPDATE The Code: int r=jTable1.getSelectedRow(); Vector row1=new Vector(); row1.addElement(txt1.getText()); row1.addElement(txt2.getText()); row1.addElement(txt3.getText()); row1.addElement(cmbClass.getSelectedItem()); row1.addElement(cmbSection.getSelectedItem()); if(opMale.isSelected()==true) row1.addElement(opMale.getText()); else row1.addElement(opFemale.getText()); modTable.removeRow(r); modTable.insertRow(r, row1); btnClear.doClick(); txt1.requestFocus(); }

Page 45: Class12 ProggAssign Answers Notes

GUI Dialogs class XII [email protected] Page 45 of 66 A dialog is a small separate subwindow that appears to either provide or request information to/from the user. Common Dialogs which we have been using so far have been: JOptionPane swing window control allows us to create pop up windows such as alerts, message boxes or input box. JOptionPane.showMessageDialog(null,”Welcome to Xavier’s”); -> displays a message and waits until the user acknowledges it by clicking OK button. JOptionPane.showInputDialog(“Enter a number”) ; -> displays a message and waits for an input from the user. The input it receives will be of type ‘String’. So if the input is a number, you will be required to convert it into int value. Now, there is another dialog which accept ‘YES’, ‘NO’ or ‘CANCEL’ input from the user and act accordingly. JOptionPane.showConfirmDialog(this,”Do you want to continue?”); -> if the user clicks ‘YES’ button a value 0 will be returned, if the user clicks ‘NO’ button a value 1 will be returned and if the user clicks ‘CANCEL’ button a value 2 will be returned.

39. Create a GUI for that will accept a series of numbers using an Input dialog box. The program should allow the user to enter numbers till he clicks ‘NO’ button in Confirm dialog box. In the end, program should display the count,sum and average of all the numbers entered. To display these values a Message dialog should be used.

Add a button and a text area control on the form. On clicking the button, the program should start asking for numbers from the user. The number entered should be added to the text area control

I am first giving you the various screenshots of the above program. The coding will follow.

If no valid number is entered at the first run, the output will be :

On clicking YES button

On clicking NO or CANCEL button

Page 46: Class12 ProggAssign Answers Notes

GUI Dialogs class XII [email protected] Page 46 of 66

On entering some numbers, the output: On clicking YES button, it will keep on prompting to enter a number.

On clicking NO or CANCEL button the program will display the result as shown:

Coding behind START button: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

int count=0; int sum=0; int cont=0; int n=0; while(true){ String s=JOptionPane.showInputDialog("Enter a Number :") ; try{ n=Integer.parseInt(s); }catch(Exception e){ cont=JOptionPane.showConfirmDialog(this,"Not a Valid Number!! Do you wish to end ??"); if(cont==0) break; else continue; }//end catch ++count; sum=sum+n; t1.append(""+n+"\n"); cont=JOptionPane.showConfirmDialog(this,"Want to continue?"); if(cont==1 || cont==2) break; } // end while String s=""; if(count!=0) s=" Sum= " + sum + "\n Count= " + count + "\n Average= " + sum/count; else s="No records entered"; JOptionPane.showMessageDialog(this, s); this.dispose(); // this line will close the form }

Page 47: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 47 of 66

if-else; for ; do – while ; while ; switch 1. Null statements are also called empty statements. These statements contains only a semicolon and

no other statements. Such statements are useful in creating ‘time delay loops’. These loops pause the program for some time. E.g. long wait =0;

while (++wait<10000) ;

2. Sequence, Selection and Iteration. Sequence means that statements are executed sequentially from top to bottom.

Selection means that the execution of the statements depend on a condition test. Iteration means repetition of a set of statements depending upon a condition test. 3. Selection means that the execution of the statements depend on a condition test. These statements

are also called as conditional statements or decision statements. Java provides if and switch as selection statements. In certain circumstance, ?: can also be used as an alternative to if statement.

?: operator can make the code little shorter, e.g. if(a> b){ z=20; } else{ z=10; } this code can be written with ?: as z=(a>b)? 20 : 10; But this can be complicated if we have too many nested if’s to check eg. if(a>b){ If(a>c){ m=a; } else { m=c;} }

if(b>c){ m=b; } else { m=c;} } with ?: above code will look like : m=(a>b: (a>c? a :c) : (b>c? b : c)); // this is little bit confusing..

4. Conditional operators are feasible where conditions to check are minimal. In cases where there are too many conditions and nested conditions are to be checked, they may prove complicated and confusing. Also the precedence of conditional operator is less than the other mathematical operators.

Default dangling else matching can be overridden by making proper use of {} braces.

5. Dangling else problem arises when in a nested if statements, number of ifs is more than the number of else clauses. The question then arises, with which if does the additional else clause property match up. In such case , java matches an else with the nearest if clause.

Eg. pg 236 q4 and q5

6. Switch and if-else statements can be used to select one of several alternatives. 7. Break statement is used to avoid ‘fall-through’ problem associated with switch statement. In ‘fall-

through’ the control falls to the matching case. When ‘break’ statement is encountered in switch statement, program execution jumps to the line of code following the ‘switch’ statement i.e. outside the body of the switch statement.

8. Switch can only test for equality whereas ‘if’ can evaluate a relational or logical expression.

If-else can handle ranges, whereas switch cannot. Each switch case label must be a single value. Switch case label must be a constant while if-else can be used when 2 or more variables are tested. Switch statements are more efficient while testing a value against a set of constants.

9. In the absence of a break statement in switch, java will start executing the statements from matching case and keep on executing statements for the following cases as well until either a break statement is found or switch statement end is encountered. This is called fall-through.

10. No two case labels in the same switch statement can have identical values. 11. The default statement gets executed when no match is found in a switch statement. 12. Iteration statements are those statements which repeats a particular set of statements a

finite/infinite number of times based on a condition . E.g. for-next, while, do-while.

Page 48: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 48 of 66 13. A loop has 4 elements namely:

o initialization expression: this is used to assign a starting value to the loop control variable. The initialization expression(s) is executed only once, at the start of the loop.

o Test expression: this expression decides whether the loop body will be executed or not. If test expression is true, the control enters the loop and executes the loop body statements otherwise the control is transferred just after the loop.

Entry controlled loop or Top-tested loop: here the test expression is evaluated first before entering the loop. Chances are that the loop body may not be executed even once. E.g. for and while loop.

Exit controlled loop or Bottom tested loop: here the test condition is evaluated at the end of the loop. This loop will be executed at least once. E.g. do-while loop.

o Update expression(s): this will change the value of loop control variable. This is evaluated at the end after the loop body is executed in the absence of this expression, the loop may be executed infinitely.

o Body of the loop: these contains the statements that will be executed repeatedly until the test expression evaluates to true.

14. It is true that you can decrement the loop control variable. But in such a case, the start value of the loop specified as initial value must be greater than the end value specified in test expression.

15. for(int i=51; i<=60;i++) S.o.p(i); 16. for(int i=10;i>=1;--i) S.o.p(i); 17. In a for loop, initialization expression(s), test expression and update expression are optional, i.e.

you can do away with any or all of these expressions. Even if you skip these expressions, the blank semi colons(;) must be given.

If a loop does not contain any statement in its loop body, it is said to be an empty loop. An empty loop is used to run a time delay loop. E.g. for(i=1; i<500; i++);

18. A variable scope is the part of the program segment where a particular variable will be visible or say can be used. It is a block of code where a variable has been declared. It can be used only within that block and all its subsequent blocks.

19. In the while loop, test expression is first evaluated and then the loop body is executed if the

condition is ‘true’. In case of do-while loop, the loop body is first executed and the test expression is evaluated at the end of the loop statement. Thus with do-while loop, the loop body will be executed at least once.

20. The ‘break’ statement terminates the smallest enclosing while, do-while, for and switch statement. Execution resumes at the statement immediately following the body of the terminated statement.

‘break [label]’ causes the flow of control to break out of the containing statement which must be labelled [label]. e.g outer: for(i=0; i<10; i++){ inner: for(j=0; j<5;j++){ break outer; } }

in the above example, the ’break outer’ statement will transfer the control after the ‘i’ loop. If it was just a ‘break’ statement, the control would have been transferred after the ‘j’ loop. 21. Labelled loops are useful as we can then use ‘break [label]’ to break out of a particular loop based

on some condition. 22. do-while loop should be used if the loop has be executed at least once and the condition has to be

checked at the end.

Page 49: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 49 of 66 23. The ‘dangling-else’ problem arises when in a nested if statement, number of if’s is more than the

number of else clauses. The question then arises, with which if does the additional else clause property matchup.

to override the default dangling – else matching is to place the last occurring unmatched if in a compound statement if(expr1){ if(expr2) statement 1; } else statement 2; in the above example, the else statement will go with if(expr1).

24.

switch(a){ case 0: S.o.p(“Zero”); break;

case 1: S.o.p(“One”); break;

case 2: S.o.p(“Two”); break;

case 3: S.o.p(“Three”); break; }

25. Java provides a multiple branch selection statement known as switch. This selection statement

successively tests the value of an expression against a list of integer or character constants. When a match is found, the statement associated with that constant are executed.

switch(expression){ case constant 1: statement sequence 1: break; case constant 2: statement sequence 2: break; case constant 3: statement sequence 3: break; case constant n: statement sequence n: break; [ default : default statement sequence : break; } ‘default’ case of the switch need not be the last one. It can be anywhere in the switch. Also there must not be two or more identical cases. It would lead to error.

26. it is a good practice to put a ‘break’ statement after the last case statement so as to avoid forgetting the ‘break’ when you add another case statement at the end of the switch.

27.

txtBasic

txtOver

txtHr

txtCCA

panPer (a panel)

txtGross txtOvertime

txtNet

Page 50: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 50 of 66

The criterion for calculation is as given below : For Temporary Employee Salary is Rs. 250 per day. OverTime is Rs. 50 per overtime hour For Permanent Employee HRA is 10% of Basic Salary CCA is Rs. 500 OverTime allowance is Rs. 75 per overtime hour. Total Amount is the sum total of Salary Amount (TxtSalary) and OverTime Amount (TxtOverTime). private void opPerActionPerformed(java.awt.event.ActionEvent evt) { panPer.setVisible(true); panTemp.setVisible(false); } private void opTempActionPerformed(java.awt.event.ActionEvent evt) { panPer.setVisible(false); panTemp.setVisible(true); } private void txtBasicFocusLost(java.awt.event.FocusEvent evt) { int basic,hra; try{ basic=Integer.parseInt(txtBasic.getText()); }catch(Exception e){ System.out.println("Invalid Basic Amount"); txtBasic.requestFocus(); return; } hra=basic*10/100; txtHr.setText(""+hra); } private void txtOverFocusLost(java.awt.event.FocusEvent evt) { int overtime; try{ overtime=Integer.parseInt(txtOver.getText()); }catch(Exception e){ System.out.println("Invalid Overtime Hours"); txtOver.requestFocus(); return; } } private void cmdCalculateActionPerformed(java.awt.event.ActionEvent evt) { int gross,net; int overtimeamt; if(panPer.isVisible()==true){ int basic=Integer.parseInt(txtBasic.getText()); int overtime=Integer.parseInt(txtOver.getText()); int hra=Integer.parseInt(txtHr.getText());

panTemp (a panel)

txtGross txtOvertime

txtNet

txtWork

txtOverTmp

Page 51: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 51 of 66 int cca=Integer.parseInt(txtCCA.getText()); overtimeamt=overtime*75; gross=basic+hra+cca; net=gross+overtimeamt; txtGross.setText(""+gross); txtOvertime.setText(""+overtimeamt); txtNet.setText(""+net); } if(panTemp.isVisible()==true){ int work=Integer.parseInt(txtWork.getText()); int overtime=Integer.parseInt(txtOverTmp.getText()); gross=(work*250); overtimeamt=overtime*50; net=gross+overtimeamt; txtGross.setText(""+gross); txtOvertime.setText(""+overtimeamt); txtNet.setText(""+net); } } private void txtWorkFocusLost(java.awt.event.FocusEvent evt) { int workdays; try{ workdays=Integer.parseInt(txtWork.getText()); }catch(Exception e){ System.out.println("Invalid Number...."); txtWork.requestFocus(); return; } } private void txtOverTmpFocusLost(java.awt.event.FocusEvent evt) { int overtime; try{ overtime=Integer.parseInt(txtOverTmp.getText()); }catch(Exception e){ System.out.println("Invalid Overtime Hours"); txtOverTmp.requestFocus(); return; }

Page 52: Class12 ProggAssign Answers Notes

Some Basic Concepts class XII [email protected] Page 52 of 66 **** coding behind ‘Check Status’ button private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { String s=""; int dd,mm,yy; s=txtOrigin.getText(); txtOrigin.setText(s.toUpperCase()); s=txtDest.getText(); txtDest.setText(s.toUpperCase()); try{ dd=Integer.parseInt(txtDD.getText()) ; mm=Integer.parseInt(txtMM.getText()) ; yy=Integer.parseInt(txtYY.getText()) ; }catch(Exception e){ JOptionPane.showMessageDialog(this,"Invalid Date...."); txtDD.requestFocus(); return; } if(dd<0||dd>31){ JOptionPane.showMessageDialog(this,"Not a valid day (1-31)"); txtDD.requestFocus(); return; } if(mm<0||mm>12){ JOptionPane.showMessageDialog(this,"Not a valid Month (1-12)"); txtMM.requestFocus(); return; } if(yy<2000||yy>2010){ JOptionPane.showMessageDialog(this,"Not a valid YEAR (2000-2010)"); txtYY.requestFocus(); return; } }

Page 53: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 53 of 66

Data Connectivity_Add_Record Assuming that you have two tables: classlist:

classtest1

1. Adding Records:

import java.sql.*; import javax.swing.*; public class Add extends javax.swing.JFrame { /** Creates new form Add */ public Add() { initComponents(); try{ conn=ConnectSv.connect(); System.out.println("Success in Connectiion"); s=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); } catch(Exception e){ System.out.println(e); } } // end constructor method Add()

Page 54: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 54 of 66 /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) { try{ rs=s.executeQuery("select * from classlist "); rs2=s2.executeQuery("Select * from classtest1"); System.out.println("success"); int t=0; while(rs.next()){ ++t; } JOptionPane.showMessageDialog(this,t); } catch(Exception e){ System.out.println(e); } } private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) { try{ rs.moveToInsertRow(); rs.updateString("regno", txtRegno.getText()); rs.updateString("roll", txtRoll.getText()); rs.updateString("std", ""+cmbStd.getSelectedItem()); rs.updateString("sec", ""+cmbSection.getSelectedItem()); rs.updateString("mf", ""+cmbMF.getSelectedItem()); rs.updateString("sname", txtName.getText()); rs.insertRow(); rs2.moveToInsertRow(); rs2.updateString("regno", txtRegno.getText()); rs2.insertRow(); System.out.println("Record Added"); }catch(Exception e){System.out.println(e); txtRegno.requestFocus(); } } private void btnAddNewActionPerformed(java.awt.event.ActionEvent evt) { txtRegno.setText(""); txtRoll.setText(""); txtName.setText(""); txtRegno.requestFocus(); }

Page 55: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 55 of 66 private void btnResetRollActionPerformed(java.awt.event.ActionEvent evt) { int n=1; String cl=""; String section=""; boolean morerecs=true; try{ rs=s.executeQuery("select * from classlist order by std,sec,sname"); System.out.println(cl+" "+section); rs.first(); while(morerecs==true){ cl=rs.getString("std"); section=rs.getString("sec"); System.out.println(cl+" "+section); while((cl.equalsIgnoreCase(rs.getString("std"))) && (section.equalsIgnoreCase(rs.getString("sec")))){ rs.updateString("roll", ""+n); ++n; rs.updateRow(); rs.next(); if(rs.isAfterLast()){ morerecs=false; break; } // end if }// end inner while n=1; }// end outer while }catch(Exception e){System.out.println(e);} } // end function /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Add().setVisible(true); } }); } Connection conn=null; Statement s,s2; ResultSet rs,rs2; // Variables declaration - do not modify private javax.swing.JButton btnAddNew; private javax.swing.JButton btnConnect; private javax.swing.JButton btnResetRoll; private javax.swing.JButton btnSave; private javax.swing.JComboBox cmbMF; private javax.swing.JComboBox cmbSection; private javax.swing.JComboBox cmbStd; private javax.swing.JLabel jLabel4; private javax.swing.JTextField txtName; private javax.swing.JTextField txtRegno; private javax.swing.JTextField txtRoll; // End of variables declaration } // end class

Page 56: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 56 of 66

Data Connectivity_Modify_Record

* @author subhashv */ import java.sql.*; import javax.swing.*; import java.util.*; import javax.swing.table.*; public class Modifications extends javax.swing.JFrame { int oldReg=0; /** Creates new form Modifications */ public Modifications() { initComponents(); try{ conn=ConnectSv.connect(); System.out.println("Success in Connectiion"); s=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); } catch(Exception e){ System.out.println(e); } } //end Modifications constructor /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked")

Page 57: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 57 of 66 private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) { try{ rs=s.executeQuery("select * from classlist " + "where std="+ cClass.getSelectedItem()+ " and sec='"+cSection.getSelectedItem() + "' order by std,sec,roll "); System.out.println("success"); rsmd=rs.getMetaData(); emptyTable(); for(int i=1;i<=rsmd.getColumnCount();++i){ modTable.addColumn(rsmd.getColumnLabel(i)); } int t=0; while(rs.next()){ ++t; Vector row=new Vector(); for(int i=1;i<=rsmd.getColumnCount();++i){ row.addElement(rs.getString(i)); } modTable.addRow(row); } rs.close(); }catch(Exception e){ System.out.println(e); } } // end btnConnect private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { int n; n=jTable1.getSelectedRow(); tRegno.setText(""+modTable.getValueAt(n, 0)); oldReg=Integer.parseInt(tRegno.getText()); // storing old regno value tRoll.setText(""+modTable.getValueAt(n, 1)); tClass.setText(""+modTable.getValueAt(n, 2)); tSection.setText(""+modTable.getValueAt(n, 3)); tMF.setText(""+modTable.getValueAt(n, 4)); tName.setText(""+modTable.getValueAt(n, 5)); } private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) { int n=jTable1.getSelectedRow(); try{ rs.absolute(n+1); rs.updateString(1, tRegno.getText()); rs.updateString(2, tRoll.getText()); rs.updateString(3, tClass.getText()); rs.updateString(4, tSection.getText()); rs.updateString(5, tMF.getText()); rs.updateString(6, tName.getText()); rs.updateRow(); System.out.println("Row "+n +" Successfully Updated"); rs2=s2.executeQuery("select regno from classtest1 where regno= "+oldReg+" order by regno"); rs2.first(); rs2.updateString(1, tRegno.getText()); rs2.updateRow(); System.out.println("Row Successfully Updated"); }catch(Exception e){System.out.println(e);} } // end btnUpdate

Page 58: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 58 of 66 void emptyTable(){ int trow=jTable1.getRowCount(); System.out.println(trow); int i=0; while(i<trow){ modTable.removeRow(0); ++i; } modTable.setColumnCount(0); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Modifications().setVisible(true); } }); } Connection conn=null; Statement s,s2; ResultSet rs,rs2; ResultSetMetaData rsmd; DefaultTableModel modTable=new DefaultTableModel(); // Variables declaration - do not modify private javax.swing.JButton btnConnect; private javax.swing.JButton btnUpdate; private javax.swing.JComboBox cClass; private javax.swing.JComboBox cSection; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField tClass; private javax.swing.JTextField tMF; private javax.swing.JTextField tName; private javax.swing.JTextField tRegno; private javax.swing.JTextField tRoll; private javax.swing.JTextField tSection; // End of variables declaration } // end class Modifications

Page 59: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 59 of 66

Data Connectivity_Add_Marks

import java.sql.*; import javax.swing.*; public class addMarks extends javax.swing.JFrame { /** Creates new form addMarks */ public addMarks() { initComponents(); try{ conn=ConnectSv.connect(); System.out.println("Success in Connectiion"); s1=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); }catch(Exception e){ System.out.println(e); } } // end addMarks constructor /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked")

Page 60: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 60 of 66 private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) { try{ rs1=s1.executeQuery("select * from classlist " + "where std="+ cClass.getSelectedItem()+ " and sec='"+cSection.getSelectedItem() + "' order by std,sec,roll "); rs1.first(); System.out.println("success"); int t=0; while(rs1.next()){ ++t; } JOptionPane.showMessageDialog(this,t); }catch(Exception e){ System.out.println(e); } } // end btnConnect private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) { try{ rs1.first(); showrec(); focus(); } catch(Exception e){ System.out.println(e); } } // end btnFirst private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {

try{ rs1.next(); showrec(); focus(); } catch(Exception e){ System.out.println(e); }

} // end btnNext private void btnPreActionPerformed(java.awt.event.ActionEvent evt) {

try{ rs1.previous(); showrec(); focus(); } catch(Exception e){ System.out.println(e); } } // end btnPre

private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {

try{ rs1.last(); showrec(); focus(); } catch(Exception e){ System.out.println(e); } } // end btnLast

Page 61: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 61 of 66 private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) { try{ if(opEng.isSelected()) rs2.updateString("eng", tEng.getText()); if(opPhy.isSelected()) rs2.updateString("phy", tPhy.getText()); if(opChe.isSelected()) rs2.updateString("che", tChe.getText()); if(opMat.isSelected()) rs2.updateString("maths", tMat.getText()); if(opInf.isSelected()) rs2.updateString("info", tInf.getText()); rs2.updateRow(); }catch(Exception e){System.out.println(e);} } // end btnSave private void opEngActionPerformed(java.awt.event.ActionEvent evt) { if(opEng.isSelected()) tEng.setEditable(true); tEng.requestFocus(); tPhy.setEditable(false); tChe.setEditable(false); tMat.setEditable(false); tInf.setEditable(false); } private void opPhyActionPerformed(java.awt.event.ActionEvent evt) { if(opPhy.isSelected()) tPhy.setEditable(true); tPhy.requestFocus(); tEng.setEditable(false); tChe.setEditable(false); tMat.setEditable(false); tInf.setEditable(false); } private void opCheActionPerformed(java.awt.event.ActionEvent evt) { if(opChe.isSelected()) tChe.setEditable(true); tChe.requestFocus(); tPhy.setEditable(false); tEng.setEditable(false); tMat.setEditable(false); tInf.setEditable(false); } private void opMatActionPerformed(java.awt.event.ActionEvent evt) { if(opMat.isSelected()) tMat.setEditable(true); tMat.requestFocus(); tPhy.setEditable(false); tChe.setEditable(false); tEng.setEditable(false); tInf.setEditable(false); } private void opInfActionPerformed(java.awt.event.ActionEvent evt) { if(opInf.isSelected()) tInf.setEnabled(true); tInf.requestFocus(); tPhy.setEditable(false); tChe.setEditable(false); tMat.setEditable(false); tEng.setEditable(false); }

Page 62: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 62 of 66 private void tEngKeyPressed(java.awt.event.KeyEvent evt) { int kc=evt.getKeyCode(); System.out.println(kc); if(kc==10){ btnSave.doClick(); btnNext.doClick(); } } private void tPhyKeyPressed(java.awt.event.KeyEvent evt) { int kc=evt.getKeyCode(); System.out.println(kc); if(kc==10){ // Enter key code btnSave.doClick(); btnNext.doClick(); } } private void tCheKeyPressed(java.awt.event.KeyEvent evt) { int kc=evt.getKeyCode(); System.out.println(kc); if(kc==10){ // Enter key code btnSave.doClick(); btnNext.doClick(); } } private void tMatKeyPressed(java.awt.event.KeyEvent evt) { int kc=evt.getKeyCode(); System.out.println(kc); if(kc==10){ // Enter key code btnSave.doClick(); btnNext.doClick(); } } private void tInfKeyPressed(java.awt.event.KeyEvent evt) { int kc=evt.getKeyCode(); System.out.println(kc); if(kc==10){ // Enter key code btnSave.doClick(); btnNext.doClick(); } } void focus(){ if(opEng.isSelected())tEng.requestFocus(); if(opPhy.isSelected())tPhy.requestFocus(); if(opChe.isSelected())tChe.requestFocus(); if(opMat.isSelected())tMat.requestFocus(); if(opInf.isSelected())tInf.requestFocus(); }

Page 63: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 63 of 66 void showrec(){ try{ tRegno1.setText(rs1.getString("regno")); String r=tRegno1.getText(); tRoll.setText(rs1.getString("roll")); tName.setText(rs1.getString("sname")); tClass.setText(rs1.getString("std")); tSection.setText(rs1.getString("sec")); tMF.setText(rs1.getString("mf")); rs2=s2.executeQuery("Select * from classtest1 where regno= '"+r+"' order by regno") ; rs2.first(); tRegno2.setText(rs2.getString("regno")); tEng.setText(rs2.getString("eng")); tPhy.setText(rs2.getString("phy")); tChe.setText(rs2.getString("che")); tMat.setText(rs2.getString("maths")); tInf.setText(rs2.getString("info")); }catch(Exception e){ System.out.println(e); } } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new addMarks().setVisible(true); } }); } Connection conn=null;; Statement s1,s2; ResultSet rs1,rs2; // Variables declaration - do not modify private javax.swing.JButton btnConnect; private javax.swing.JButton btnFirst; private javax.swing.JButton btnLast; private javax.swing.JButton btnNext; private javax.swing.JButton btnPre; private javax.swing.JButton btnSave; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox cClass; private javax.swing.JComboBox cSection; private javax.swing.JRadioButton opChe; private javax.swing.JRadioButton opEng; private javax.swing.JRadioButton opInf; private javax.swing.JRadioButton opMat; private javax.swing.JRadioButton opPhy; private javax.swing.JTextField tChe; private javax.swing.JTextField tClass; private javax.swing.JTextField tEng; private javax.swing.JTextField tInf; private javax.swing.JTextField tMF; private javax.swing.JTextField tMat; private javax.swing.JTextField tName; private javax.swing.JTextField tPhy; private javax.swing.JTextField tRegno1; private javax.swing.JTextField tRegno2; private javax.swing.JTextField tRoll; private javax.swing.JTextField tSection; // End of variables declaration } // end class addMarks

Page 64: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 64 of 66

Data Connectivity_View_Record

import java.sql.*; import java.util.*; import javax.swing.table.*; import javax.swing.*; public class vueMarks extends javax.swing.JFrame { /** Creates new form vueMarks */ public vueMarks() { initComponents(); try{ conn=ConnectSv.connect(); System.out.println("Success in Connectiion"); s1=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); s2=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); }catch(Exception e){ System.out.println(e); } } // end vueMarks constructor /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try{ String c=""+cClass.getSelectedItem(); String s=""+cSection.getSelectedItem(); rs1=s1.executeQuery("select * from classlist as c,classtest1 as ct " + "where c.regno=ct.regno and std= "+c+" and sec='"+s+"' order by std,sec,roll "); System.out.println("success"); emptyTable(); rsmd=rs1.getMetaData(); for(int i=1;i<=rsmd.getColumnCount();++i){ modTable.addColumn(rsmd.getColumnLabel(i)); }

Page 65: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 65 of 66 int t=0; while(rs1.next()){ ++t; Vector row=new Vector(); for(int i=1;i<=rsmd.getColumnCount();++i){ row.addElement(rs1.getString(i)); } modTable.addRow(row); } rs1.close(); }catch(Exception e){ System.out.println(e); } } // end jButton1 void emptyTable(){ int trow=jTable1.getRowCount(); System.out.println(trow); int i=0; while(i<trow){ modTable.removeRow(0); ++i; } modTable.setColumnCount(0); } private void jTable1MouseClicked(java.awt.event.MouseEvent evt) { int n; n=jTable1.getSelectedRow(); int en,ph,ch,ma,in; int tot; double per; try{ en=Integer.parseInt(""+modTable.getValueAt(n, 7)); }catch(Exception e){ en=0;} try{ ph=Integer.parseInt(""+modTable.getValueAt(n, 8)); }catch(Exception e){ ph=0;} try{ ch=Integer.parseInt(""+modTable.getValueAt(n, 9)); }catch(Exception e){ ch=0;} try{ ma=Integer.parseInt(""+modTable.getValueAt(n, 10)); }catch(Exception e){ ma=0;} try{ in=Integer.parseInt(""+modTable.getValueAt(n, 11)); }catch(Exception e){ in=0;} tot=en+ph+ch+ma+in; per=tot/250.0*100; tTotal.setText(""+tot); tPercent.setText(""+per); } // end JTable1MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vueMarks().setVisible(true); } }); } Connection conn=null; Statement s1,s2; ResultSet rs1,rs2; ResultSetMetaData rsmd;

Page 66: Class12 ProggAssign Answers Notes

Data Connectivity class XII [email protected] Page 66 of 66 DefaultTableModel modTable=new DefaultTableModel(); // Variables declaration - do not modify private javax.swing.JComboBox cClass; private javax.swing.JComboBox cSection; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField tPercent; private javax.swing.JTextField tTotal; // End of variables declaration }