Posts

Showing posts from August, 2020

FOR LOOP WITH CHALLENGES

Image
FOR LOOP   Syntax :   for ( int i= 0 ; i< 6 ; i++){                     System . out .println( "Loop " + i + " hello" );                     }

NUMBER OF DAYS IN A MONTH

 Write a method called isLeapYear with a parameter of type int named year . The parameter needs to be greater than or equal to 1 and less than and equal to 9999. If the parameter is not in that range return false. Otherwise, if it is in the valid range, calculate if the year is a leap year and return true if it is, otherwise returns false. [A year is a leap year if it is divisible by 4 not by 100, or it is divisible by 400] Write another method getDaysInMonth with two parameters month and years. Both of type int If parameter month is < 1 or > 12 return -1 If parameter year is < 1 or > 9999 return -1 This method needs to return the number of days in month. be careful about leap years (29 days in Feb) [Use switch statements] Soln   package com.cnc ; public class Main { public static void main ( String [] args) { System . out .println( isLeapYear (- 2000 )); System . out .println( getDaysInMonth (- 2 , 2000 )); } public static boolean isLeapYear ( i

IF ELSE V/S SWITCH STATEMENT

 BY IF ELSE STATEMENT package   com.cnc ; public class Main { public static void main ( String [] args) { printDayOfTheWeek ( 3 ); } public static void printDayOfTheWeek ( int day) { if (day == 0 ) { System . out .println( "sunday" ); } else if (day == 1 ) { System . out .println( "monday" ); } else if (day == 2 ) { System . out .println( "tuesday" ); } else if (day == 3 ) { System . out .println( "wednesday" ); } else if (day == 4 ) { System . out .println( "thursday" ); } else if (day == 5 ) { System . out .println( "friday" ); } else if (day == 7 ) { System . out .println( "saturday" ); } else { System . out .println( "invalid" ); } } } BY SWITCH CASE STATEMENT public class Main { public static void main

CHALLANGE SWITCH STATEMENT

 Create a new switch statement using char instead of int.      "     "    ''      char varia

SWITCH STATEMENT

  package com.cnc ; public class Main { public static void main ( String [] args) { int switchValue = 1 ; switch ( switchValue ){ case 1 : System . out .println( "value was 1" ); break ; case 2 : System . out .println( "value was 2" ); break ; case 3 : System . out .println( "value was neither 1 nor 2" ); break ; default : System . out .println( "Was not 1 or 2" ); } } } Both if statement and switch statement can achieve the same. 

PLAYING CAT

 The cat spends most of the day playing. In particular, they play if the temperature id between 25 and 35 (inclusive). Unless it is summer, the upper limit is 45 (inclusive) instead of 35. Write a method of isCatPlaying that has two parameters. The method needs to return true if it is playing, otherwise, return false. 1st parameter is of type boolean and is named summer it represents summer. 2nd is named temperature of type int representing the temperature. Soln :   package   com.cnc ; public class Main { public static void main ( String [] args) { System . out .println( isCatPlaying ( true , 10 )); System . out .println( isCatPlaying ( false , 36 )); System . out .println( isCatPlaying ( false , 35 )); } public static boolean isCatPlaying ( boolean summer, int temperature) { if (summer){ if (temperature<= 45 && temperature>= 25 ) { return true ; } else return false ; } else

MINUTES TO YEAR AND DAYS CHALLENGE

 Write a method printYearsAndDays with parameters of type long named minutes. The method should not return anything and it needs to calculate years and days from the minutes parameter. If the parameter is less than 0, print text "INVALID VALUE". Otherwise, print in the format  "XX min = YY y and ZZ d". Soln        package  com.cnc ;      public class Main { public static void main ( String [] args) { printYearsAndDays ( 525600 ); } public static void printYearsAndDays ( long minutes){ if (minutes< 0 ){ System . out .println( "Invalid Value" ); } else { long years = minutes/( 60 * 24 * 365 ); long days = minutes/( 24 * 60 ); long remainingDays = days % 365 ; System . out .println(minutes+ " min =" + " " + years + " y and " + remainingDays + " d" ); } } }

SECOND AND MINUTES CHALLENGE

Create a method called getDurationString with two parameters, first parameter minutes and 2nd seconds You should validate that 1st parameter is >=0   ''        ''            ''         ''    2nd       ''        '' >=0 and <=59 The method should return invalid in the method if either of the above is not true   If parameters are valid then calculate how many hours minutes and seconds equal the minutes and seconds passed to this method and return that value in the format as "XXh YYm ZZs". Create a second method of the same name but only one parameter seconds. If it is valid, then calculate how many minutes are in second value and then call the overloaded method passing the correct minutes and seconds calculated so that it can calculate correctly  Call both methods on the console. Soln :           package  com.cnc;    public class Main { public static void main ( String [] args) { getDurationString ( 65 , 45 );

CALCULATE FEET AND INCHES TO CENTIMETRES

  Create a method called calcFeetAndInchesToCentimeters.It needs to have two parameters feet and inches.You should validate the first parameter feet is >=0 and inches is >=0 and <=12 which return -1 from the method if either of the above is not true. If parameters are valid, then how many centimeters comprises the feet and inches passed to this method and return that value.Create a 2nd method of the same name but with only one parameter inches. validate that it is >=0, return -1 if false. But if its valid, then  calculate how many feets are in inches and here is the tricky part call the other overloaded method passing the correct feet and inches calculated so that it can calculate correctly. HINTS: Use 1inch = 2.54 cm and 1ft = 12inches. Soln:   package com.cnc ; public class Main { public static void main ( String [] args) { calcFeetAndInchesToCentimeters ( 3 , 1 ); calcFeetAndInchesToCentimeters (- 1 , 3 ); calcFeetAndInchesToCentimeters ( 100 );

57 METHOD OVERLOADING

If a  class  has multiple methods having the same name but different in parameters, it is known as  Method Overloading .   There are two ways to overload the method in java By changing the number of arguments By changing the data type 1) Method Overloading: changing no. of arguments In this example, we have created two methods, first, add() method performs addition of two numbers and second add method performs addition of three numbers. In this example, we are creating  static methods  so that we don't need to create an instance for calling methods. class  Adder{   static   int  add( int  a, int  b){ return  a+b;}   static   int  add( int  a, int  b, int  c){ return  a+b+c;}   }   class  TestOverloading1{   public   static   void  main(String[] args){   System.out.println(Adder.add( 11 , 11 ));   System.out.println(Adder.add( 11 , 11 , 11 ));   }}   2) Method Overloading: changing data type of arguments In this example, we have created two methods that differ in  data type . The fi

Decimal Comparator

 Write a method areEqualByThreeDecimalPlaces with two parameters of double The method should return boolean and it needs to return true if two double decimal numbers are the same up to three decimal places. Otherwise, return false Example         areEqualByThreeDeciamlPlaces(-3.125,-3.1259)-----> true           areEqualByThreeDeciamlPlaces(-3.125,-3.139)----> false Soln:     package com.cnc ; public class Main { public static void main ( String [] args) { System . out .println( areEqualByThreeDecimalPlaces (- 3.125 , - 3.1259 )); } public static boolean areEqualByThreeDecimalPlaces ( double firstNumber, double secondNumber) { if (( int ) (firstNumber * 1000 ) == ( int ) (secondNumber * 1000 )) { return true ; } return false ; } }

Leap year Challange

 Write a method isLeapYear with a parameter of type int named the year the parameter needs to be greater than or equal to1and less than or equal to 9999 if the parameter is not in the range return false. Otherwise, if it is in the valid range, calculate if the year is a leap year and return true if it is a leap year, otherwise return false to determine follow these steps--- if the year is divisible by 4 then go to step 2. Otherwise, go to step 5. if  year is divisible by 100 then go to step 3. Otherwise, go to step 4. if  year is divisible by 4 then go to step 2. Otherwise, go to step 5. this is a leap year. the method isLeapYear return true. this is not a leap year. the method isLeapYear return false. Soln                        package com.cnc ;           public class Leap_Year_Test { public static boolean isLeapYear ( int year) { if (!(year >= 1 && year <= 9999 )) { return false ; } else {

48 CHALLENGE 3

 Create a method called display HighScorePosition .It should a player's name as a parameter, and the 2nd parameter as a position in the high score table. You should display the player's name along with a message like "manage to get into position" and the position they got and a further message "on the high score table". Create a 2nd method called calculatedHighScorePositon it should send one argument only, the player score and it should return an int the return data score should be 1 if the score is.>=1000 2 if score is >=500 and<1000 3 if the score is >=100 and<500 4 if in all other cases call both methods and display the following score of 1500, 900, 400 and 50 Soln:    package com.cnc ; public class Main { public static void main ( String [] args) { int position = calculatedHighScorePosition ( 1500 ); displayHighScorePosition ( "Chinmoy" ,position); position = calculatedHighScorePosition ( 900 );

47 METHODS IN JAVA

  package com.cnc ; public class Main { public static void main ( String [] args) { calculateScore ( true , 800 , 5 , 100 ); calculateScore ( true , 600 , 10 , 200 ); } public static void calculateScore ( boolean gameOver, int score, int levelCompleted, int bonus){ if (gameOver){ int finalScore = score +(levelCompleted*bonus); finalScore += 1000 ; System . out .println( "your final score is " +finalScore); } } }

45 CHALLENGE 2

 Print out a second score on the screen with the following  the score set to 10000 levelCompleted set to 8 bonus set to 200  soln: package com.cnc ; public class Main < gameOver > { public static void main ( String [] args) { boolean gameOver = true ; int score = 10000 ; int levelCompleted = 8 ; int bonus = 200 ; if ( gameOver ){ int finalScore = score +( levelCompleted * bonus ); System . out .println( "your final score is " + finalScore ); } } }

45 IF - ELSE CONTROL STATEMENT

  package com.cnc ; public class Main { public static void main ( String [] args) { int male = 32 ; int female = 70 ; if ( male < 18 ){ System . out .println( "An child boy" ); } else if ( male >= 18 && male <= 60 ){ System . out .println( "An adult boy" ); } else { System . out .println( "An old man" ); } if ( female < 18 ){ System . out .println( "An child girl" ); } else if ( female >= 18 && female <= 60 ){ System . out .println( "An adult girl" ); } else { System . out .println( "An old woman" ); } } }

43 KEYWORDS AND EXPRESSIONS

  package com.cnc ; public class Main { public static void main ( String [] args) { double km = ( 100 * 1.609344 ); //datatype //expression(var,val,operators) int highScore = 50 ; if ( highScore == 50 ){ System . out .println( "this is an expression" ); } } int highScore = 50 ; entire line is the statement & highScore = 50 the expression

39 CHALLENGE OPERATOR

 1 CREATE A DOUBLE VAR OF 20.00 2 CREATE A SEC VAR OF TYPE DOBLE 80.00 3 ADD BOTH NOs AND MULTIPLY BY 100.00 4 USE REMAINDER OPERATOR TO FIGURE OUT THE REMAINDER FROM THE RESULT OF THE OPERATION IN STEP 3 AND 40.00. WE USED THE MODULUS OPERATOR ON INTS IN COURSE,BUT  WE CAN ALSO USE THE DOUBLE. 5 CREATE A BOOLEAN VAR THAT ASSIGNS TRUE IF THE REMAINDER IN #4 IS 0 OR FALSE IF ITS NOT ZERO. 6OUTPUT BOOLEAN VAL. 7 WRITE AN IF ELSE STATEMENT THAT DISPLAYS A MESSAGE "GOT SOME REMAINDER'. package com.cnc ; public class Main { public static void main ( String [] args) { double a = 20.00d ; double b = 80.00d ; double c = a + b ; double e = c * 100 ; double rem = e % 40.00d ; boolean g = ( rem == 0 ) ? true : false ; System . out .println( "The remainder is " + rem ); if (! g ) { System . out .println( "Got some remainder" ); } } } OUTCOME The remainder is 0.0

37 ASSIGNMENT OPERATOR VS EQUAL TO OPERATOR

  package com.cnc ; public class Main { public static void main ( String [] args) { int newValue = 50 ; if (newValue = 50 ){ //we are not assigning the value System . out .println( "this is an error" ); } int newValue1 = 50 ; if ( newValue1 == 50 ){ //we are not assigning the value but we are testing if newValue1 is equal to 50 or not System . out .println( "Error is removed by using == in newValue1" ); } boolean isCar = false ; if ( isCar = true ){ System . out .println( "This is not supposed to happen in car" ); } boolean isCar1 = false ; if ( isCar1 == true ){ System . out .println( "This is fine and we are using == sign in car1 " ); } boolean isCar2 = false ; if (! isCar2 ){ System . out .println( "This is fine and we are using ! sign in car2 " ); }

36 LOGICAL "OR" OPERATOR

  OR--------> ONLY ONE  STATEMENT NEEDS TO BE TRUE  package com.cnc ; public class Main { public static void main ( String [] args) { if (( topScore > 90 ) || ( secondTopScore )<= 90 ){ System . out .println( "Either or both of the condition are true" ); } } }

35 LOGICAL "AND" OPERATOR

AND--------> BOTH STATEMENT TRUE OTHERWISE FALSE   package com.cnc ; public class Main { public static void main ( String [] args) { int topScore = 100 ; if ( topScore == 100 ) { System . out .println( "You got the Highest Score for 1st test" ); } int topScoreNot = 100 ; if ( topScoreNot != 100 ) { System . out .println( "You got the Highest Score foe 2nd test" ); } int topScoreGreaterThan = 100 ; if ( topScoreGreaterThan >= 99 ) { System . out .println( "You got the Highest Score for 3rd test" ); } int topScoreLessThan = 77 ; if ( topScoreLessThan <= 100 ) { System . out .println( "You Score is less than 100 in 4th test" ); } int secondTopScore = 77 ; if ( ( topScore > secondTopScore ) && ( topScoreLessThan < 100 ) ){ //&&---> true when both the con