Feb 12, 2012

[Java] method with return values

// Java
// method with return values


import java.util.*;

class method_with_return
{

// A java program must start with "main" method
 public static void main(String[] args)    // main method
 {
 
        System.out.println("first number?");
        Scanner scan1 = new Scanner (System.in);
        
        while(!scan1.hasNextDouble())
        {
            scan1.next();  // if input is not integer value, ignore it.
            System.err.println("Input should be number");
        }
        double n1=scan1.nextDouble(); 
        
        System.out.println("second number?");
        Scanner scan2 = new Scanner (System.in);
        
        while(!scan2.hasNextDouble())
        {
            scan2.next();  // if input is not integer value, ignore it.
            System.err.println("Input should be number");
        }
        double n2=scan2.nextDouble(); 

        if(n1==0 && n2==0) {
            bye();    // if weight was input 0, call method "bye"
            System.exit(0); }
                
        
        System.out.println("What do you want?  (1) multiply, (2) divide");
        Scanner scan3 = new Scanner (System.in);
        
        while(!scan3.hasNextInt())
        {
            scan3.next();  // if input is not integer value, ignore it.
            System.err.println("Input should be 1 or 2");
        }
        int op=scan3.nextInt(); 


        if(op==1)
        {    System.out.println();        
            System.out.println(n1 + " * " + n2 + " = " + function1(n1, n2));  
        } else 
            {
                System.out.println();        
                System.out.println(n1 + " / " + n2 + " = " + function2(n1, n2));  
            }
}


 public static double function1(double n1, double n2)
 {
        return n1*n2;
 }
 
  public static double function2(double n1, double n2)
 {
        return n1/n2;
 }
 
 public static void bye()
 {
        System.out.println();        
        System.out.println("Good Bye");
 }
}

No comments:

Post a Comment