You are on page 1of 18

CSE 101 Spring 2012

Lab7 Methods

1.

Write a method which calculates the average of three input integers. Write the main program as well and call the method. A. Put a breakpoint in marked line and run the program in debug mode. Add all variables, x,y,z and and a,b,c to watch window. Now watch the program flow and variables by stepping into method. Observe that x,y,z is only defined in main and a,b,c is defined only in method. Also observe that the stack window shows the list of method calls when you are in the method, and when you step out to the main, the method averageThreeints is erased from the list. Now repeat the debug mode run again, watch the variable average in main scope, and ave in method. When the average takes value, when we loose ave from the scope.

B.

A) import java.util.Scanner; public class Lab7_1{ public static void main(String args[]){ int x = 5; int y = 10; int z = 3; double average = averageThreeints(x,y,z); System.out.println("The average of "+x+","+y+","+z+" is "+ average); } // main ends

public static double averageThreeints(int a, int b, int c){ double ave; ave = (a+b+c)/3.0; return ave; } // method ends No need to explain the logic behind } // class ends

this program as it is aimed to show how methods run. Just ask to write it as it is.

1.B) Add these mistakes/modifications to the previous program one by one and observe the compiler messages/errors and correct them. Write return; instead of return ave Define int ave instead of double Change the position of class end brace } put it after main brace} Erase the end method brace Erase modifiers public and static of method. Erase one of the parameters from the method averageThreeints(int a, int b); Erase datatypes for the parameters averageThreeints(int a,b,c); Erase one of the arguments of method call, e.g. averageThreeints(x,y); Ignore the return value, e.g. erase double average= Call the method directly in println. Copy and paste the method before main method. Copy and paste the method before class.
import java.util.Scanner; public class Lab7_1{ public static void main(String args[]){ int x = 5, y = 10; int z = 3; double average = averageThreeints(x,y,z); System.out.println("The average of "+x+","+y+","+z+" is "+ average); } // main ends public static double averageThreeints(int a, int b, int c){ double ave; ave = (a+b+c)/3.0; return ave; } // method ends } // class ends

2) Write a method which doubles a given integer value. Observe and discuss the difference between mkdouble1 and mkdouble2, and then two different calls to mkdouble2.

import java.util.Scanner; public class Lab7_2{

public static void makeDouble1(int a){ a =a*2; }


public static int makeDouble2(int a){ a =a*2; return a; }//end of method

public static void main(String[]args){ Scanner kb = new Scanner(System.in);


System.out.println("Enter N:"); int n = kb.nextInt(); System.out.println(n+ before); makeDouble1(n); System.out.println(n+ after mkdbl2); makeDouble2(n); System.out.println(n+ after mkdbl2); n = makeDouble2(n); System.out.println(n+ after mkdbl2); }

} //end of class

Write a method which produces a random number between two given integer values.

Write a main method to demonstrate the use of your method, make sure that it really creates random numbers between your given range.

import java.util.Scanner; public class Lab7_4{ public static int randomIntinRangeab(int a, int b){ return ((int) (a+ Math.random()*(b-a+1))); } public static void main(String[]args){ Scanner kb = new Scanner(System.in);

System.out.println("Enter a:"); int low = kb.nextInt(); System.out.println("Enter b:"); int high = kb.nextInt(); int a = 0; while ((a++)<100) System.out.println(a+".random integer: "+randomIntinRangeab(low,high));
} }

3) Write a method which calculates and returns factorial of a given integer. Complete the program with main, which asks the user to enter an integer, and invokes the method that computes the factorial. Run the program and see how it works. Debug the program using a breakpoint and observe the program flow. See how n value changes inside the method; what is the value of the n outside of the program; explain why n is not affected, why it is not 0 outside. only for CSE101.04

Use the common main method that contains test statements for almost all questions.

public static long fact(int n){ long res = 1; for(int i=1;i<=n;i++) res*=i; return res; }

Write a Java program that asks the user to enter x, then calculates ex using a loop to add up successive terms until the current term is less than 1.0E-12. (Midterm question)

Remember that you already have fact() method.

public static double midtermQ(int x){ double res = 1.0; double term=x; int i =1; while(term>=1.0E-12){ res+=term; i++; term = ((Math.pow(x, i))/fact(i)); } return res; }

Write the below methods, and program(s) to test them.


public static boolean allTheSame(int a, int b, int c) //returns true if the arguments are all the same public static int firstDigit(int num) //returns the first (most significant) digit of its argument

public static boolean allTheSame(int a, int b, int c){ if(a==b&& b==c) return true; else return false; } public static int firstDigit(int num){ //returns the first (most significant) digit of its argument int last; while(num!=0){ last = num%10; num=num/10; } return num; }

Palindromic Prime: A palindromic prime is a prime number and also palindromic. For example, 131 is a prime and also a palindromic prime. So are 17 and 71. Write a program which displays the first 100 palindromic prime numbers. Display 10 numbers per line and align the numbers properly.
public static boolean isPrime(int num) { if ((num == 1) || (num == 2)) { return true; } for (int i = 2; i <= num / 2; i++) { if (num % i == 0) { return false; } } return true; } public static int reversal(int num) { int result = 0; while (num != 0) { int lastDigit = num % 10; result = result * 10 + lastDigit; num = num / 10; } return result; } public static boolean isPalindrome(int num) { return num == reversal(num); } }// end class

public class PalindromePrime { public static void main(String[] args) { int count = 1; for (int i = 2; true; i++) { // Display each number in five positions if (isPrime(i) && isPalindrome(i)) { System.out.print(i + " "); if (count % 10 == 0) { System.out.println(); } if (count == 100) { break; } count++; // Increase count } // end if } // end for } // end main

7) Lets create a set of methods which we can use from other programs. In this tutorial we will create two separate files one for our library of methods, another one for our main program. Compile and run the main program (Try for other and observe compiler msg). Call all three methods one by one and debug using step-into.
// Save this in CSE101Util public class CSE101Util{ // this method aveages three integer values public static double averageThreeints(int a, int b, int c){ double ave; ave = (a+b+c)/3.0; return (ave); } // this method calculates and returns the max value public static int maxThreeints(int a, int b, int c){ if( (a>=b) && (a>=c)) return a; else if ( (b>=a) && (b>=c)) return b; else return c; } // this method calculates and returns the min value public static int minThreeints(int a, int b, int c){ if( (a<=b) && (a<=c)) return a; else if ( (b<=a) && (b<=c)) return b; else //if ( (c<=a) && (c<=b)) return c; } }

// Save this in Lab6_7 import java.util.Scanner; public class Lab6_7{ public static void main(String [] args){ Scanner kb= new Scanner (System.in); int a = kb.nextInt(); int b = kb.nextInt(); int c = kb.nextInt(); System.out.println(the average: + CSE101Util.averageThreeints(a,b, c)); System.out.println(the max:+CSE101Util.maxThreeints(a,b, c)); System.out.println(The min+CSE101Util.minThreeints(a,b, c)); } }

To be covered only in CSE101.i && i==4

Self study
public static //returns the public static //returns the int lastDigit(int num) last(least significant) digit of its argument int digits(int num) number of digits of its argument

Having a secure password is a very important practice as we store too much information online. Write method(s), and test program that validates a new password following the rules. The password:
must be at least 8 characters long. Must have at least one uppercase, and one lowercase letter Must have at least one digit.

public static boolean checkDigit(String pass){ boolean result = false; for(int i=0;i<pass.length();i++){ if(pass.charAt(i)=='1' || pass.charAt(i)=='2' || pass.charAt(i)=='3' || pass.charAt(i)=='4' || pass.charAt(i)=='5' || pass.charAt(i)=='6' || pass.charAt(i)=='7' || pass.charAt(i)=='8' || pass.charAt(i)=='9'||pass.charAt(i)=='0'){ result = true; break; } } return result; } public static boolean checkUpperLower(String pass){ return checkUpper(pass) && checkLower(pass); }

public static boolean checkUpper(String pass){ boolean oneCapital = false; //convert all chars into lowercase dGwlei --> dglei String passLower = pass.toLowerCase(); for(int i=0;i<pass.length();i++){ //at least one char must be different if(pass.charAt(i)!=passLower.charAt(i)){ oneCapital = true; break; } } return oneCapital; } public static boolean checkLower(String pass){ boolean oneLower = false; //do the same for checking lowercase String passCapital = pass.toUpperCase(); for(int i=0;i<pass.length();i++){ //at least one char must be different if(pass.charAt(i)!=passCapital.charAt(i)){ oneLower = true; break; } } return oneLower; }

You might also like