-2

I am trying to build a simple program that will keep doing it until a certain conditional is met. In this case whether it is true or false. I've been playing around with it for a while, but I still can't get it to work as I want.

import java.util.Scanner;

public class oddeven {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a number: ");

        int num = scan.nextInt();
        boolean play = true;
        String restart = " ";

        do {
            if((num % 2) == 0) {
                System.out.println("That number is even!");
            } else {
                System.out.println("That number is odd!");
            }

            System.out.println(
               "Would you like to pick another number? (Type 'yes' or 'no')");

            restart = scan.nextLine();

            if(restart == "yes") {
                System.out.println("Enter a number: ");
                play = true;
            } else {
                System.out.println("Thanks for playing!");
                play = false;
            }
        }
        while(play == true);
    }
}
Reporter
  • 3,547
  • 5
  • 28
  • 45

1 Answers1

0

Here is the code for what you are trying to do. You have been doing 3 to 4 things wrong, see the code and you will understand.

And you should also see this link

What's the difference between next() and nextLine() methods from Scanner class?

http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html

import java.util.Scanner;

class test {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        boolean play = true;
        do {
        System.out.println("Enter a number: ");
        int num = Integer.valueOf(scan.next());
        String restart = " ";
            if ((num % 2) == 0) {
                System.out.println("That number is even!");
            }
            else {
                System.out.println("That number is odd!");
            }
            System.out.println("Would you like to pick another number? (Type 'yes' or 'no')");
            restart = scan.next();
            if (restart.equalsIgnoreCase("yes")) {
                play = true;
            }
            else {
                System.out.println("Thanks for playing!");
                play = false;
            }
        } while (play == true);
    }
}
Abhishek Honey
  • 603
  • 4
  • 13