methods in java with examples

0

method / function

A function takes parameters and returns a value. A method is a specific type of function: it must be  part of a class, so has access to the class member variables. A function is usually discrete and all variables must be passed in.

 

For example:

Function version - InitiateTrade(person, stock, price)

Method version - person.InitiateTrade(stock, price)

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

 

Example of a function that prints a hello world statement:

public class Methods_in_java {
    public static void printHello()//function definition
    {//function body
System.out.println("hello world");
    }
    public static void main(String[] args) {
printHello();  //function call
printHello();  //function call
printHello();  //function call
  }
}

 

 

All Contributions

Write a method named Calculator that accepts three variables, two int arguments and one character for operation. The method should return the result for this operation. write a program to test your method.

 

java code:

import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
char operator = input.next().charAt(0);
System.out.println("Enter first number");
double number1 = input.nextDouble();
System.out.println("Enter second number");
double number2 = input.nextDouble();
System.out.println(number1 + " "+operator +" "+ number2 + " = " +
Calculator(number1,number2,operator));
}
public static double Calculator (double n1,double n2,char op){
double result=0;
// performs opreations between numbers
switch(op){
case '+':result=n1+n2;break;
case '-':result=n1-n2;break;
case '*':result=n1*n2;break;
case '/':result=n1/n2;break;
default : System.out.println("Invalid input");
}
return result;
}
}

Write a method named isEven that accepts an int argument. The method should return true if the argument is even, or false otherwise. Write a program to test your method.

 

java code:

import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter a number: ");
int number=input.nextInt();
if (isEven (number))
System.out.println("The number "+number+" is even.");
else
System.out.println("The number "+number+" is odd.");
}
public static boolean isEven (int n){
if(n%2==0)
return true;
else
return false;
}
}

Write a program with a method named getPrice that accepts two doubles (price , amount) as an argument and return price. Call this method from main( ) and print the results. Hint: Price = Price * amount

 

java code:

import java.util.Scanner;
public class Lab6 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Enter the number of items: ");
int num=input.nextInt();
System.out.print("Enter the price: ");
int unitprice=input.nextInt();
System.out.print("The price is: " + getPrice(unitprice,num));
}
public static double getPrice (double price,double amount){
return price*amount;
}
}

write java program to check login info of the user, program should do that using a method called "login", its inputs are username and password, and its output is a boolean value indicates if login info is correct or wrong

*hint: in the login method you should use equals() method to compare between Strings

user have 3 try times to enter his login his username and password.

output should be like this:

your login info, you have remaining 3 try times
username: 
adam 
password: 
1234567
login info is wrong, you have 2 try times remaining
your login info, you have remaining 2 try times
username: 

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

answer:

import java.util.Scanner;
public class Main
{
    public static boolean login(String username,String password)//function declaration
    {
        //function body:
        String correctUsername="ads2100",correctPassword="987763";
        if(username.equals(correctUsername) && password.equals(correctPassword))
        return true;
        else return false;
    }
    
	public static void main(String[] args) {
	    Scanner input=new Scanner(System.in);
	    int remainingTryTimes=3;
	    String u,p;
	    boolean result;
	    do{
	        System.out.println("your login info, you have remaining "+remainingTryTimes+" try times");
	        System.out.println("username: ");
	        u=input.next();
	        System.out.println("password: ");
	        p=input.next();
	        result=login(u,p);
	        if(result==true)
	        {
	            System.out.println("login info is correct, you will signin now...");
	            System.out.println("welcome "+u);
	            break;
	        }
	        else {
	            remainingTryTimes--;
	            System.out.println("login info is wrong, you have "+remainingTryTimes+" try times remaining");
	        }
	    }
	    while(remainingTryTimes>0);
	}
}

method arranges 3 numbers from smallest to largest and then prints them:

(Sort three numbers) Write a method with the following header to display three numbers in increasing order:

public static void displaySortedNumbers( int num1, int num2, int num3)

Write a test program that prompts the user to enter three numbers and invoke the method to display them in increasing order.

class Main {

public static void displaySortedNumbers(int a,int b, int c)
{
  int min, max, med;
if( a > b ){
 if( a > c ){
  max = a;
  if( b > c ){
   med = b;
   min = c;
  }else{
   med = c;
   min = b;
  }
 }else{
  med = a;
  max = c;
  min = b;
 }
}else{
 if( b > c ){
  max = b;
  if( a > c ){
   med = a;
   min = c;
  }else{
   med = c;
   min = a;
  }
 }else{
  med = b;
  max = c;
  min = a;
 }
}
System.out.println(min+"\n"+med+"\n"+max);
}

  public static void main(String[] args) {
    System.out.println("Hello world!");
    displaySortedNumbers(543, 334, 765);
  }
}

total contributions (6)

New to examplegeek.com?

Join us