>

Sunday, December 16, 2012

Simple Java programs

1.
Question :
Given two non-negative int values, return true if they have the same last digit, such as with 27 and 57. Note that the % "mod" operator computes remainders, so 17 % 10 is 7.

Ans:
public boolean lastDigit(int a, int b) {
          int r=a%10;
        int r1=b%10;
        if(r==r1)
        {
            System.out.println(true);
        }  // These programs for educational purpose only. Dont copy and publish in your blog or website..
        else
            System.out.println(false);
}

2.

Question :Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

Ans:
public boolean posNeg(int a, int b, boolean negative) {
  if((a<0&b>0&negative==false)|(a>0&b<0&negative==false))
        {
            System.out.println(true);
        }
        else if(a<0&b<0&negative==true)
            System.out.println(true); 
        else
            System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..


3.
 Question :
Given two temperatures, return true if one is less than 0 and the other is greater than 100.

icyHot(120, -1) → true
icyHot(-1, 120) → true
icyHot(2, 120) → false

Answer:
public boolean icyHot(int temp1, int temp2) {
  if((temp1<0&temp2>100)|(temp1>100&temp2<0))
        {
            System.out.println(true);
        }
        else
            System.out.println(false);
} // These programs for educational purpose only. Dont copy and publish in your blog or website..

No comments:

Post a Comment

Please post your comments. Your comments make us to write more programs for you.