0

The question is
Write a method isMultiple that determines, for a pair of integers , whether the second integer is a multiple of the first. The method should take two integer arguments and return true if the second is a multiple of the first and false otherwise.

[Hint: Use the remainder operator .] Incorporate this method into an application that inputs a series of pairs of integers (one pair at a time) and determines whether the second value in each pair is a multiple of the first.har()

Here is my code

import java.util.*;
public class Multiples {

    public static void main(String [] args){

        boolean run = true;

        while(run = true){
        System.out.print("Enter one number:");
        Scanner input = new Scanner(System.in);

        int num1 = input.nextInt();
        int num2 = input.nextInt();

        System.out.println("Do you want to enter another pair(y/n)?");
        String a = input.next();



        boolean result = isMultiple(num1, num2);

        if(result = true){
            System.out.println(num1 + " is a multiple of " + num2);
        }
        else{
            System.out.println(num1 + " is not a multiple of " + num2);
        }

        if(YesOrNo(a)){
            break;
        }


        }


    }

        public static boolean YesOrNo(String a){

            if(a == "y")
              return false;
            else if(a == "n")
              return true;
            else
                return true;
        }


        public static boolean isMultiple (int x , int y)
        {
             if(x % y == 0 || y % x == 0)
                 return true;   
             else
                 return false;

        }


    }

I want break the while when enter "n" but it is break no matter what I enter.

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
King
  • 13
  • 1
  • 2
  • There are more than one error. Look at `while(run = true)` and `if(result = true)`. The `=` operator is an *assignment*. What you most probably want to do is comparing, i.e. use `==`. But it’s easier to write `while(run)` and `if(result)` to avoid such errors. Your main problem is the `String` comparison using `==` instead of `equals`, however saying `else return true` when the input is neither `"n"` nor `"y"` made it worse. And, don’t write `if(condition) return true; else return false;` as `return condition;` is much clearer. – Holger Oct 01 '14 at 22:41

1 Answers1

0

Thats because this:

if(a == "y")
    return false;
else if(a == "n")
    return true;
else
    return true;

will always execute the else part. Which means that YesOrNo(a) will always be true and will always break the loop.

This happens because you cannot compare Strings using the == operator.

Change it to this instead :

if(a.equals("y"_)
    return false;
else if(a.equals("n"))
    return true;
else
    return true;
gkrls
  • 2,618
  • 2
  • 15
  • 29