Java Puzzles to Eliminate Code Fear

A method is a set of code

 

variable
string
return
void
method
String
-equals
-equalsIgnoreCase
-Indexof
-LastIndexOf
-!equals
-String.substring
char
TestingUtils.runTests()
Conditionals

 

Scenario:
We have a loud barking dog. The “hour” parameter is the current hour time in the range 0 to 23. We are in trouble if the hour is before 7 or after 20. Return true if we are in trouble

While Loop:

code:

package practice.loop;


public class whileLoop {
    public static void main(String[] args) {
        String str="Me have a large inventory of things in our warehouse falling in "+"the category:appearal and the slightly"+"more in demand category:makeup along with the category:furniture and";
        printCategories(str);
    }


    public static void printCategories(String str)
    {
        int i=0;
        while(true){
            int found=str.indexOf("category:",i);
            if(found==-1)
                break;
            int start=found+9;
            int end=str.indexOf(" ",start); //finding the word from start
            System.out.println(str.substring(start,end));
            i=end+1;
        }
    }

}

output:

appearal
makeup
furniture

For Loop:

package practice.loop;

public class forLoop {
    public static void main(String[] args) {
        String string1="zakilive";
        for(int i=0; i<=string1.length()-1; i++)
        {
            System.out.println("char:"+string1.charAt(i));
        }
    }
}

Reverse character:

package practice.loop;

public class forLoop {
    public static void main(String[] args) {
        String string1="zakilive";
        for(int i=string1.length()-1; i>=0; i--)
        {
            System.out.println("char:"+string1.charAt(i));
        }
    }
}

Print  even number from 0 to 100:

package practice.loop;

public class forLoop2 {
    public static void main(String[] args) {
        for(int i=0; i<=100; i=i+2)
        {
            System.out.println(i);
        }
    }
}

Sending parameters as an array

package practice.loop;

public class ArrayPracticeNew {

    public static void main(String[] args) {
        int[] values = new int[]{2, 2, 4, 5, 6, 7};
        System.out.println(search((values), 5));
        System.out.println(search(new int[]{2, 3, 4, 5, 6, 7}, 9));
    }

//it should return the index position if it is not then it return -1
    public static int search(int[] nums, int target) {
        int ret = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target)
                ret = i;
        }
        return ret;
    }
}

Cool recursion example instead of loop:

package practice.loop;

public class RecursionAssignmentSolution {
    public static void main(String[] args) {
//        String myString=new String("lets learn java");
//        System.out.println(myString.substring(1));
//        System.out.println(myString.substring(1,3));
        
        System.out.println(allDollars("hello")); //h$e$l$l$o
        System.out.println(allDollars("james")); //j$a$m$e$s
    }

    public static String allDollars(String str){
        if(str.length()<=1){
            return str;
        }
        return str.charAt(0)+"$"+allDollars(str.substring(1));
    }
}

SpeedingFine Assignment:

my logic:

/**
	 * You are driving a little too fast, and a police officer stops you. 
	 * Write code to compute the fine you would have to pay. 
	 * If your speed is 60 or less, the result is 0 since there is no fine. 
	 * If speed is between 61 and 80 inclusive, the fine is 100 dollars. 
	 * If speed is 81 or more, the result is 200. 
	 * Unless it is a holiday -- on that day, your speed can be 5 higher in all cases. <br>
	 * <br> 
	 *
	 * <b>EXPECTATIONS:</b><br>
		speedingFine(60, false)  <b>---></b> 0 <br>
		speedingFine (65, false)   <b>---></b> 100 <br>
		speedingFine (65, true) <b>---></b> 0 <br>
	 */
		public static int speedingFine(int speed, boolean isHoliday) {
			int fine=0;
			if(!isHoliday)
			{
				if(speed<=60)
					fine=0;
				if(speed>=61 && speed<=80)
					fine=100;
				if(speed>=81)
					fine=200;
			}else{
				if(speed<=65)
					fine=0;
				if(speed>365 && speed<=85)
					fine=100;
				if(speed>=86)
					fine=200;
			}

				return fine;
		}

 

We always try to make the code short and sweet: Logic from the course instructor

public static int speedingFine(int speed, boolean isHoliday) {
			int minSpeed=60;
			int maxSpeed=80;
			int fine=0;

			if(isHoliday)
			{
				minSpeed+=5;
				maxSpeed+=5;
			}

			if(speed>=maxSpeed)
				fine=200;
			if(speed<=minSpeed)
				fine=0;
			if(speed>minSpeed&&speed<=maxSpeed)
				fine=100;


			return fine;
		}

Short and sweet code:

public static int speedingFine(int speed, boolean isHoliday) {
			if(isHoliday)
			{
				speed-=5;
			}
			if(speed<=60)
				return 0;
			if(speed>60 && speed<=80)
				return 100;
			else
				return 200;

		}

 

Another logical problem:

The birds in Florida like to sing during favorable temperatures. 
	In particular, they sing if the temperature is between 60 and 90 (inclusive). 
	Unless it is summer, then the upper limit is 100 instead of 90. 
	Given an int temperature and a boolean isSummer, 
	return true if the birds are singing and false otherwise. <br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		birdsSinging(70, false)   <b>---></b> true <br>
		birdsSinging(95, false)    <b>---></b> false <br>
		birdsSinging(95, true) <b>---></b> true <br>
	 */
	public static boolean birdsSinging(int temp, boolean isSummer) {

		boolean booleans = false;
		if(isSummer) {
			if (temp >= 60 && temp <= 100)
				booleans = true;
		}
		else{
			if(temp>=60&&temp<=90)
				booleans=true;
		}
		return booleans;
	}

Singing code by me:

	public static boolean birdsSinging(int temp, boolean isSummer) {

		boolean booleans = false;
		if(isSummer) {
			if (temp >= 60 && temp <= 100)
				booleans = true;
		}
		else{
			if(temp>=60&&temp<=90)
				booleans=true;
		}
		return booleans;
	}

Also by ternary operator in one line:

public static boolean birdsSinging(int temp, boolean isSummer) {
		return (isSummer)?(temp>=60 && temp<=100):(temp>=60 && temp<=90);
}
/**
	Given three ints, first, second, third, return true if second is greater than first, and third is 
	greater than second. However, with the exception that if the parameter "itsOk" is true, 
	second does not need to be greater than first but still better be less than third.
	<br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		isOrdered(1, 2, 4, false)   <b>---></b> true <br>
		isOrdered(1, 2, 1, false)    <b>---></b> false <br>
		isOrdered(1, 1, 2, true) <b>---></b> true <br>
	 */
	public static boolean isOrdered(int first, int second, int third, boolean itsOk) {
		boolean val = false;
		if(itsOk) {
			if (second < third) {
				val = true;
			}
		}
		else {
			if((second > first)&&(third > second)){
				val=true;
			}

		}
		return val;
	}

In one line with ternary operator

		return (itsOk)?(second < third):((second > first)&&(third > second));

Ass_06:

	/**
	We'll say a number is cool if it's a multiple of 11 or if it is one more than a multiple of 11. 
	Return true if the given non-negative number is cool. Use the % "modulus" operator 
	we spoke about in the prerequisite section. Watch the lesson on modulus if you need to review
	<br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		isCool(22)   <b>---></b> true <br>
		isCool(23)    <b>---></b> true <br>
		isCool(24) <b>---></b> false <br>
	 */
		public static boolean isCool(int n) {

			return n%11==0||n%11==1;
}

Amar VuulVaal code:

	//	public static String fizzyWizzy(int n) {
//		    if(n%3==0)
//		        return "Fizz!";
//		    else if(n%5==0)
//		        return "Buzz!";
//		    else if((n%3&&n%5)==0)
//		        return "FizzBuzz!";
//		    else
//		    	return n + "!";
//		}

 

Valo code FizzyWizzy :P::

	/**
	Given an int n, return the string form of the number followed by "!". 
	So if the int is for example 13 this method should return "13!". 
	However the catch is that if the number is divisible by 3 the method should return "Fizz!" 
	instead of the number, and if the number is divisible by 5 it should return "Buzz!", 
	and if divisible by both 3 and 5, use "FizzBuzz!". You’ll need to use the % "mod" 
	for computing the remainder after division, so 23 % 10 yields 3. 

	<br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		fizzyWizzy(1)   <b>---></b> "1!" <br>
		fizzyWizzy(2)    <b>---></b> "2!" <br>
		fizzyWizzy(3) <b>---></b> "Fizz!" <br>
	 */	


public static String fizzyWizzy(int n){
		boolean fizz=n%3==0;
		boolean buzz=n%5==0;

		if(fizz&&buzz) return "FizzBuzz!";
		if(fizz) return "Fizz!";
		if(buzz) return "Buzz!";

		return n+"!";
	}
Given 3 int arguments - a, b, c, return their sum. However, if one of the arguments 
	is the same as any of the other ones, that number should not count towards the sum. 
	So basically you only sum unique numbers, not duplicates
	<br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		sumUnique(1, 2, 3)   <b>---></b> 6 <br>
		sumUnique(3, 2, 3)    <b>---></b> 2 <br>
		sumUnique(3, 3, 3) <b>---></b> 0 <br>
	 */
	
	public static int sumUnique(int a, int b, int c) {

		if (a == b && b == c) return 0;
		if (a == b) return c;
		if (c == a) return b;
		if (b == c) return a;

		return a + b + c;

Assignment_09 my own solution:

/**

	Given 2 positive int arguments (a, b), return whichever argument is 
	nearest to the number 21 without going over.
	Return 0 if they both go over 21. 
	<br>
	<br>

	 * <b>EXPECTATIONS:</b><br>
		nearestTwentyOne(19, 21)   <b>---></b> 21 <br>
		nearestTwentyOne(21, 19)    <b>---></b> 21 <br>
		nearestTwentyOne(19, 22) <b>---></b> 19 <br>
		nearestTwentyOne(32, 22) <b>---></b> 0 <br>
	 */
	
	public static int nearestTwentyOne(int a, int b) {
		int val=0;
		if(a>21 || b>21)
			val=0;
		if(a>21&&b<=21)
			val=b;
		if(a==21||b==21)
			val=21;
		if(a<21&&b>21)
			val=a;
		if(a<21&&b<21)
		{
			if(a<b)
				val=b;
			if(a>b)
				val=a;
		}
		return val;
	}

Logic from the instructor:

public static int nearestTwentyOne(int a, int b) {
		if(a>21&&b>21) return 0;
		if(a>21&&b<=21) return b; //a is disqualified
		if(a<=21&&b>21) return a; //b is disqualified

		if(a>b)
			return a;
		else
			return b;

	}

 

 

 

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.