Logic and Loops Practice Comments

Comments

  • Haha, LOL! I can't solve it now, it's funny! But I solve the problem some other way, I created my own version of code with another logic:

    import java.util.Scanner;

    cont...
  • there some kind of mistake? Method contain two params, why does it can calculating with only one param?????

  • if a and b are the same, then its essentially one parameter. (a+b) * 2 is the same as a * 4

  • Dude can someone please post the answer..

  • Really simple stuff. For those of you stuck on this, remember order of operations and == other than that this should be a piece of cake with some ice cream.

  • I copied the answer in and it was still incorrect... what dafuq this site has bugs and it's teaching me how to code? what is this.

    if(a==b){
        return a * 4;
    }
    else{
        return a+b;
    }
    
  • @Cherry, you left out the closing curly bracket of the method when you copied the code.

  • The problem is with the last set of parameters. It is 2 and 2 and expects an 8, when in fact it should expect a 4.

  • Very interesting. I went further to add an extra if statement that allows only numbers between 1 and 6.

  • here's mine :

    import java.util.Scanner;

    public class Main {

    static int doStuff(int a, int b){
        //your code here
        if(a!=b)
            {
                return a+b;
            }
        else
            {
                return (a+b)+(a+b);
            }
    }
    
  • I do it. It was interesting.

  • Please can someone help. I can't figure out what I'm doing wrong in this question.
    Here is my code
    import java.util.Scanner;

    public class DiceRolling {

    cont...
  • this is so simple...use the same logic as you used in earlier challange of if else.....
    ie;
    if (a==b){
    return (a+b)*2;
    }else
    return (a+b);
    }

  • Random rand = new Random();

        int a = rand.nextInt(7);
        int b = rand.nextInt(7);
    
  • An interesting thing I discovered in this task is that you can't use return statements within a switch-block otherwise the compiler will say the break statements are unreachable. I had to assign

    cont...
  • @Victoria, thanks. If you use a return statement, you should remove the break after it, since return exits the block of code. To help avoid errors, the Java compiler doesn't accept code it recognizes as unreachable (even if just a break statement).

  • You can make an String array and a new String after which you can do the following if for example num == 1 then assign the value of array[0] which is "one" in which case the new String equals "one". For too large and too small assign the "too large" or "too small" string from array if num < 1 and if num > 4 assign those strings from array to new String. Close all if and else if statements and return the new String.

    cont...
  • Is there an easier way to do this? For the numbers 1-4 and other conditions, i made an individual if statement to save the string value to a variable. It seems kind of inefficient to write 6 if statements.

  • @alan, you can use a switch case instead. Click on "Featured Answers" above the Hint.

  • Need help
    import java.util.Scanner;

    public class Main {

    public static String doStuff(int num){
        //your code here
        for(int i = 1; i < 5; i++){
    
    cont...
  • My solution is:

    String mes = "";
    String[] onetofour = {"one", "two", "three", "four"};
    for (int i =1; i<onetofour.length+1; i++) {
    if (num== i) {

    cont...
  • public static String doStuff(int num){
        //your code here
        String[] str = {"too small", "one", "two", "three", "four", "too large"};
        if(num < 1){
            return str[0];
        }
        else if(num > 4){
            return str[5];
        }else{
            return str[num];
        }
    }
    
  • My solution and it is correct :
    String result="";
    String [] test = {"one","two","three","four"};
    if (num 4) result= "too large";

    cont...
  • This continuation of "if" and "else" problems doesn't explain how to convert numbers to text. Can you please explain?

  • You need to return a String.

  • Can I get an explanation on how to return a string? Like I said this wasn't covered in previous lessons.

  • Instead of return 5;, you do return "hello"; See String Class for more info.

  • I keep getting errors in the code I didn't write and I haven't touched the boiler plate code.

    import java.util.Scanner;

    public class Main {

    public static String doStuff(int num){
    
    cont...
  • Never mind got it although I don't know if the way I did it is the most efficient. Thanks love this site!!!!

  • what is wrong with this code:

        String number;
            switch(num){
            case 1:
                number= "one";
                break;
            case 2:
                number= "two";
    
    cont...
  • this code works in eclips?

  • I think i have a very good queston ( at least i hope so).

    Why isnt declaring enough en should i initialize the string. so
    String message=""; works ( initializing)
    String message; does not work, why not? for a string it does not mather right. i get it if it was an int but now??

  • What is wrong with this code?

    textDef = ["Too small","One","Two","Tree","Four","Too large"]
    def printText (num):
    if num<1:
        print (textDef[0])
    elif num>4:
        print (textDef[5])
    else:
        print(textDef[num])
    
    printText(2)
    
  • My solution

    if(num < 1) return "too small";
    if(num > 4) return "too large";
    
    String[] words = {"one","two","three","four"};
    return words[num-1];
    
  • LOL had to go back to Booleans chapter.... people Booleans is different from booleans, careful when defining your boolean.

  • I tries using only booleans but didn't work for all conditions, the following worked for me.
    if (gold>=pirates &&gold+pirates <100){
    return true;
    }
    else{
    return false;
    }
    }

  • I had the following it worked.

    my code

  • My solution
    return(!(gold+pirates > 100) && gold >= pirates);

  • Only this works.

    return gold >= pirates && gold+pirates < 101;
    
  • return gold+pirates>100?false:gold>=pirates?true:false;
    works for me

  • please fix If there's at least as much gold as pirates, that's good. it should if the gold is greater but cannot divided equal to pirates

  • if someone is having trouble with inconpatible types (boolean/integer) pay attention to:

    public static boolean doStuff(int gold, int pirates)

    Hope it helps :)

  • I am having big trouble with inconpatible types (boolean/integer);
    even when I replace cheet answer...?!!?!

    Main.java:7: error: incompatible types
    return 0;
    ^
    required: boolean
    found: int

  • @saeed, the header of your method should say static int doStuff, not static boolean doStuff

  • "If there's at least as much gold as pirates, that's good (even though the gold cannot be divided equally)" this would produce 1 at the input 10 10

  •              if (pirates > gold || pirates + gold > 100) return 0;
        else if (gold%pirates == 0) return 2;
        else return 1;
    
  • return (gold100)?0:gold%pirates==0?2:1;

    if you want to do it in one line

  • Completed, but won't check off.

  • Ha, I was just using this formula working only with int values:
    x = (1000*15)/100

  • Just gotta say that thanks for including quotes, it keeps me somewhat interested and inspired at the same time while going through this awesome noob training. Pura vida!

  • int[] ar = {0,5,10,15,20,25};
        return (a * ar[b])/100;
    
  • ahahaha :D i don't understand the instructions????
    hmpff guess so ... i couldn't figure out why those are the outputs ... -.-
    can someone explain the instructions ? hehehe :)

  • ahhhh okey got it myself ehehe :D anyways thanks :)

  • double f= b*.05; // .05, .1, .15, .2, .25
    double c= a*f;
    return (int)c;

  • If you just use doubles instead of integers then integers become doubles.
    example 5/2=2 but 5/2.0=2.5

    my code

  • I don't understand the proplem!!!

  • I don't understand the problem.

  • You just need to calculate the tip according to the given table. The tip should be a percentage of the the total purchase. I added an example to make it clearer.

  • easy peoples
    import java.util.Scanner;

    public class Main {

    static int doStuff(int a, int b){
    
        switch(b)
        {
            case 1:
                return (int)(a*0.05);
    
    cont...
  • how can this be wrong?

  • solved it, it was just a bracket to much ( luckely not a bridge to far :-))

  • Solved, It's really Easy.
    static int doStuff(int a, int b){
    int sum = a + b;
    if (sum>21){
    return 0;
    }else{
    return sum;
    }
    }

  • you can do it in a single line ex

    return (a+b > 21)? 0 : a+b; // just like that.

  • Perfect, makes sense. Thanks!

  • It's really simple but not boring, great!

  • Bug on last entry with javascript for both BlackJack 1 and BlackJack 2: when read the last line I get "7 11", but after I use parseInt my function receives 7 and 1.

  • if 11 is converted to 1, last correct output is wrong.

  • @Borja, it is only converted to 1 if it will otherwise overshoot 21.

  • Shame on me :) got totally focused on converting 11 to 1. Thanks for pointing out

  • Can't figure out how to convert the correct output to 13 and 14 with the correct code. Everything I tried does a compilation error.

  • Lets say i have 11 and 11. then automaticly it wil return 12. but perhaps i am a weird player of somekind and i want it to be 2. In the casino i can choose this if i want, here i cant?

    my code

  • why compilation fails error ? my code

  • if((a+b)<22 && a!=11 && b!=11){
    return a+b;
    }
    if(a==11 || b==11){

                if((a+b)>21){
                    if(a==11)
                    a=1;
                    if(b==11)
                    b=1;
                }
    
    
                return a+b;
            }
    
        return 0;
    
  • very simple....
    return a+b<21?a+b:(a==11||b==11)?a+b-10:0;

  • return a+b>21?(a==11?b+1:(b==11?a+1:0)):a+b;

  • One way to do it:

    int sum = a+b;
    int one = 1;

        if(sum>21){
    
            if(a == 11){
                return one+b;
            }
            if(b == 11){
                return one+a;
            }
                return 0;
        }
    
        return sum;
    }
    
  • For input set 5 3 19, we can get 19 using 3 pennies and 4 nickels. So it should be true there.

  • Sorry, I mistook nickels and pennies...

  • 5, 4, 23 will result false !!!!!! it ca't be true 5*5 +4 = 24 ?????????????????

  • @Amboss, the challenge is to see if you can select the exact change from the coins you are given. So if you have 5 nickels, you can select 4 of them, add 4 pennies for a sum of 24 cents.

  • I've made the code, but when I run table below shows that all cases are correct EXCEPT that "Your Output" is incorrect, it's red.
    I don't know why, I checked some made up cases manually on Eclipse.

  • Кирилл, When given 7 nickels and 3 pennies, can you get 35 cents? Yes, you just select the nickels and ignore the pennies. Check your code to see what it returns.

  • Admin (?), I've make some changes, even few, but still, there is something wrong. Your example works, thanks for it!)
    I'm just curious where I get lost.

  • Кирилл. there's another example you're getting wrong. I think you should approach this problem a little differently. You can solve it with one if-else statement.

  • You can solve it with one if-else statement.
    You're right. And only now it's shows "Correct". I have to say that with no mathematical help I won't do that. So, on my opinion this problem more related to mathematics rather then to programming.

  • OMG :( this took me forever also my code is extensive.... looks like complying with DRY is going to take me looong time to master.

  • At the end of my program I write << return boolean; >> but program say error:

    variable bool might not have been initialized
    return bool;

  • I found my solution;
    when I defined boolean bool I must give amount to it LIKE boolean bool = false;

  • I archived many comments here with solutions. You can link to your solution (in your submissions) to share it, but you shouldn't paste the whole solution in here.

  • @mistermase nice. See also the featured answer

  • i'm confused i'm not familiar with nickel and pennies and cents -.- do they have relationships with each other ? like how many cents are there in pennies or in nickel ? :)

  • American Currency^ LOL

  • For those of you in different countries: Pennies are 1 cent, Nickles are 5 cents (each).

  • Added a note to main content on their value.

  • I think i have a good solution? is it a smart solution?

    my code

  • OK, but see the featured answers for a more concise answer.

  • I wrote my code in python. it's working if i run this in some other compiler but here it's not.
    my code

  • Boilerplate code for this challenge wasn't provided for Python, so you need to take in the input yourself from STDIN.

  •     int nCount = sum / 5;
        if (nCount <= nickels) {
            return sum % 5 <= pennies;
        } else {
            return false;
        }       
    
  • int a=sum/5;
    int b=sum%5;
    if(nickels>=a && pennies>=b){
    return true;
    }
    return false;

  • if ((sum%nickels) > pennies) return false;
        return true;
    

    how the heck did this pass all the tests..

  • Thanks, that's actually an edge case that wasn't covered before. The last test case will now check that condition so that code no longer passes.

  • I did this way
    if(nickels>=sum/5 && pennies>=sum%5)
    {
    return true;
    }
    else
    {
    return false;
    }

  • Here's some working boilerplate for Ruby:

    n = gets.chomp.to_i
    n.times do
    input = gets.chomp.split(" ").map(&:to_i)
    nickels = input[0]
    pennies = input[1]
    desired_sum = input[2]
    print correct_change?(nickels, pennies, desired_sum), "\n"
    end

  • All of them work except for Other input which gives me Your Output instead of Other Output.
    ????

  • Other input and Other Output are additional cases that aren't displayed on this page. For example, given 5 nickels and 5 pennies, can you reach a sum of 35? Its not possible, but your code returned true.

  • I have the same problem. All examples are correct but other input/output isn't. What's wrong with my code? Cant think of a case in which it wouldn't work. It would work with the 5 nickels, 5 pennies and sum 35 example.

  • @peter, what if you were given 100 nickels, 200 pennies but you needed to get 701 cents? What would your program return then and what should it?

  • Thx, because of the example you have given I was able to find what had to be added to the code. Maybe you should add it to the core I/O instead of other I/O.

  • Cool i actually did not have to modify my code from the previous example, the same one worked :)

  • How you must write a good program:
    First:Solve the problem yourself
    Second:Change your resolution to code exactly
    Third:Simplify your code by getting your necessary final conclusion without doing whole operation

  • This one was quite the challenge, but I finally figured it out!
    .
    .
    .
    boolean yes=false;
    for (int i=0; i<=nickels; i++){
    if (5*(nickels-i)<=sum){

    cont...
  •     if(sum%5 > pennies) {
            return false;
        }
        return nickels*5 + pennies >= sum;
    
  • public static boolean doStuff(int nickels, int pennies, int sum){
        for (int i = 0; i <= nickels; i = i + 1) {
            if ( sum - 5 * i <= pennies && sum - 5 * i >= 0) {
                return true;
            }
        }
    
        return false;
    }
    
  • public static boolean doStuff(int nickels, int pennies, int sum){
    int a=sum/5;
    if(a>nickels){
    a=nickels;
    }

        int b=sum-(a*5);
        if(pennies>=b){
            return true;
        }
        return false;
    }
    
  • With my code, Im able to get all correct except the last one with 7, 7, 44..why would it not work?

  • Boiler plate code for ruby:

    ruby
    n = gets.chomp.to_i
    n.times do
    input = gets.chomp.split(" ").map(&:to_i)
    nickels = input[0]
    pennies = input[1]
    desired_sum = input[2]
    print correct_change?(nickels, pennies, desired_sum), "\n"
    end

  • I can't even imagine using mod operator "to see if a number ends in 7". Web search didn't helped too.
    Also, I do not see a reason to check if number divides by 7.

  • I do not see a reason to check if number divides by 7.

    I got it.Then I put my code and it all works. It's just a mess of statements.
    Now I see Explanation below, it's so easy now using only one if statement!

  • This is weird for me, it works until the number 14. How can it be the case?

  • @Davin, for specific feedback from admins on your code, consider signing up for membership or the bootcamp.

  • For finding out if the number ends with 7 you should check (number % 10) != 7

  • What is the correct phrasing for the print function. I keep getting an error when trying to test my code? Thanks

  • I keep getting errors in part of the code that I'm not altering. Can I please get some help on this? Thanks

  • This usually means you've changed the boilerplate code. In such a case, carefully copy your actual code, click "reset" and try again.

  • I keep getting an "cant find symbol error" when I try to print my int.. I'm going to have to cheat on this one. sigh

  • I think I would like to get recognition for possibly having devised the longest, clunkiest and ugliest answer so far:

    my code

  • Ha, now I see the pitiful 3 lines of code given as the official answer...That won't cut it.
    [insert smiley emoticon here.]

  • Completed successfully, not checked off on the side list, though.

  • My code works fine! Admin, thanks you for explanation part after the task, picked up something new!

  • Not checked off as well

  • @Davin, did it get checked off when you went to the next page?

  • 'import java.util.*;

    public class Main{

    public static void main(String[] args) {
    
    
        for (int i=0; i<=100; i = i+1){
    
    cont...
  • I did mine a different way does it mean my code isn't as efficient or wrote very well?

  • There are many ways to solve this problem. Run-time efficiency doesn't matter for such small problems, but it's important to try to write clear code. See the featured answers for another possible solution.

  • my solution:
    for(int i=1;i<=100;i++){

            String a=i%5==0?"Buzz":"";
             String b=i%3==0?"Fizz":"";
            System.out.println(b.length()+a.length()!=0?b+a:i);
    
        }
    
  • for(int i=1;i<=100;i++){

            String a=i%5==0?"Buzz":"";
             String b=i%3==0?"Fizz":"";
            System.out.println(b.length()+a.length()!=0?b+a:i);
    
        }
    
  • My stupid
    else if((i%3 ==0) && (i%5==0)){
    System.out.println("FizzBuzz");
    }

    doesn't seem to give FizzBuzz for 15! Why? GRRR

  • I'm not sure what to do with the "Other Input" part. Can get everything else to work but don't know what is expected for "Other Input".

  • @Kirsten, it now shows all 4 cases.

  • Great, thanks!! That was a super quick fix : )

  • I think there could be a problem with this exercise. It was working fine on the previous page with the hard-coded numbers, but since changing these to the variables n, a and b for this advanced

    cont...
  • @Victoria, in this challenge you need to print each word space-separated and only add new lines after each test case. See the "Correct Output" shown above.

  • Thanks, that worked. :)

  • What I did is, make a string and assign values to it inside if statements in a for loop and if a certain condition was met than the string was changed to Fizz or Buzz and printed out, else I printed the number i which is <= n

    Hope it helps. :P

  • How shoud I define a,b and n?

  • @saeed, I added a note about the input format.

  •     Scanner in = new Scanner(System.in);
    
        int loops = in.nextInt();
    
        for (int i = 0; i < loops; i++) {
    
            int max = in.nextInt();
    
    cont...
  • my code
    Hey, guys. I got through the last challenge no problem. I also know how to use the Scanner for input, but it doesn't seem to want to run my code based on

    cont...
  • You can use the provided boilerplate code to take in input, you don't need your own scanner. Note that each case consists of 3 numbers, n, a and b. Print out n items for each case.

  • no featured answer? I know my code sucks, so I'd like to see how it could be done better.

  • Featured answer added.

  • Excellent.

  • Confused about declaring n, a, and b. Normally in these challenges these are already declared, but I don't see it in this code. Here is the code I'm using which is which throws a compilation error, even though the same code worked on the previous challenge when n = 100, a = 3, and b = 5:

    cont...
  • You can't just compare to n without having declared and assigned it. You need to declare the variables yourself (or use actual numbers.)

  • I'm expecting t to be an int....
    "The input starts with T, the number of cases."

    but it compile errors because it says T is a string!

  • Since this challenge involves standard input, you may want to use the boilerplate code to process the input for you.

  • Does ^ not mean "to the power of" in java? I kept trying i2 but that didn't work, so I did i*i and that did.

  • @jacknerik, ^ does not do "power" in Java. You can see the Java's main built-in math operations here: http://www.learneroo.com/modules/11/nodes/103. Your way was good, though there is also the

    cont...
  • I've entered this code
    for (int i = a; i <= b; i ++)
    {
    return (i * i);
    }

    when I run the program it tells me I am missing a return statement.

  • for(int m=a; m<b; m=m+1){
            if(m>a&&m<b){
                return m*m+b*b+a*a
    

    someone explain why my code is wrong.

  • Hint: Use a variable to keep track of the total sum and return that at the end.

  • @Learneroo I tried creating an int that represents the total. For some reason my int that represents the numbers in the range only picks up the first number in the set. Can you explain what I'm doing wrong?

  • @Bernard, create a variable sum before the loop, and then add the square of each number to sum. Then return sum after the loop.

  • @learneroo when you say create a variable. Do you mean create an int variable? And if so I'm given only the first and last number how can I express the numbers in the range in an int? I was thinking a++.

  • Yes, create an int variable. Then loop through the numbers from a to b. If you need more help see this code and modify it to add the squares instead of the numbers. See also Math with loops for more practice.

  • @leaneroo when i plug in the provided code given in the above comment i get an error. I'm gonna work on it still just wanted to let you know. Thanks

  • @learneroo , Finally got it but I don't quite understand still. In my equation does sum remain zero even as the loop goes on. I recall in past nodes that sum changes as the loop goes on. I may be wrong though. Thanks

  • sum is declared outside the loop and set to 0, the loop modifies its value, so after the loop it has the value of whatever it was at the end of the loop. See also scope.

  • Why does this result in "Execution timed out. Please fix your code to execute faster."?

    static int doStuff(int a, int b){
        int sum = 0;
        for (int i=a;a<=b;i++) {
            int aPow = a*a;
            int bPow = b*b;
            sum += (aPow*bPow);
        }
        return sum;
    }
    
  • Check if the loop will ever terminate. Will there be cases where a will never be less than b, so that the loop goes on forever?

  • Thanks. I just re-read my code after sleeping and can't believe I even wrote that.

  • import java.util.Scanner;

    public class Main {

    static int doStuff(int a, int b)
    {
            int count=b;
            int  ans=1;
    
         for(int i=0;i<b;i++)
    
    cont...
  • That was tricky. Took me! my code

  • Quite simple, one problem was to stop the toop, eventually I've managed it.

  • For me it wasn't about stopping the loop but actually how to get the number print the first time(initial input) and the last time (1) without having the loop interfering.

  • Whats wrong with my code? It keeps giving me the "Runtime error"

    public static void doStuff(int num){
        System.out.print(num + " ");
        while(num > 1){
    
    cont...
  • @Mikas Your else says "num = num * 3 - 1" it should be +1.

  • I dont understand why would 3-1 cause runtime error?

  • @Jig, you can get stuck in a loop, eg 5, 14, 7, 20, 10, 5 ...

  • How did you know that it would get stuck in a loop. Thanks for the insight. Love what you guys are doing.

  • @Learneroo should I create two loops?

  • @Bernard, that's not necessary. You can create one while loop, with a condition inside it that determines what number to go to next.

  • your correct output's are wrong.
    for input=5 , the output should be 16 8 4 2 1

  • Sorry, due to a change yesterday it was mistakenly showing the number 5 for the count, it's been fixed.

  • Three examples above shows correct, but "other output" is wrong. Maybe I misunderstood the task, maybe it's better to show more examples in I/O.

  • @zkvarz, you can now view more cases.

  • Thank you for cases, admin! I think this way:
    5 10, answer is 10.
    In this case we can't divide 5 evenly so we divide 10 until we get smallest even number 2, therefore 5*2 = 10.

  • so we divide 10 by 5. I still can't get it, why not 2

  • Admin, I thought I get this task but still, "other output" is wrong. Something I do the wrong way.

  • Dear Admin,

    On the Explanation:

    "Explanation: You could use a while loop, or a compact for loop:

    int i;
    for(i=1; a*i % b != 0; i = i +1 ){

    cont...
  • @David, i will keep increasing until a*i is a product of b. So it will stop when i=5 and a=3 and return that product.

  • import java.util.Scanner;

    public class Main {

    static int doStuff(int a, int b)
    {
    
        int max=1;
        for(int i=2;i<=a;i++)
        {
            if(a%i==0 && b%i==0)
    
    cont...
  • A little difficult

  • This worked for me but I don't understand it, anyone please explain

        int multiple =0;
        for(int i=1; i<=100; i++){
            multiple=a*i;
    
            if (multiple%b ==0 && multiple%a==0){
                return multiple;
    
            }
        }
        return multiple;
    
  • int c=0; 
        while(c%b!=0){
            c=c+a;
        }
        return c;
    

    I don't understand why my code isn't working.

  • If c is 0 , what happens when you reach the while condition? (You should always test out smaller parts of your code to know what's going on.)

  • Is this a smart solution. I mean it does makes a different if a<b or b<a right?

    my code

  • int LCM = 1;
    while (!(((LCM % a) == 0) && ((LCM % b) == 0))){
    LCM++;
    }
    return LCM;

Contact Us
Sign in or email us at [email protected]