简体   繁体   中英

Dr.Java related to ASCII Displayer

I want to generate a sequence of numbers where: I want to compute the next number in the sequence by: (if the number is even, divide it by 2) and (if the number is odd multiply it by 3 and add 1).

I am using ASCIIPrompter and I input the starting number which is 29.

The final display should repeatedly display the number in the sequence and generate the next number based on the conjecture above. The problem with my code is "num = even" gives me an error and i dont know how to fix this error. HELP IS GREATLY APPRECIATED THANKS.

import java.awt.*; // for Color class
import static BasicIO.Formats.*; // for getCurrencyInstance, etc.
import static java.lang.Math.*; // for math constants and functions & random
import static java.awt.Color.*; // for Color constants (e.g. RED)

public class sequence {

    private ASCIIDisplayer display;
    private ASCIIPrompter prompt;

    public sequence() {

        display = new ASCIIDisplayer();
        prompt = new ASCIIPrompter();
        int num;
        prompt.setLabel("starting Number");
        num = prompt.readInt();
        for (int i = 1; i <= 5; i++) {
            if (num = even) {
                num = num / 2;
            } else {
                if (num = odd) {
                    num = num * 3 + 1;
                }
            }
            display.writeDouble(num);
        }
        display.close();
        prompt.close();

    }; // constructor

    public static void main(String[] args) {
        sequence c = new sequence();
    };
}

= is an asssignment

if (num = even) {

Thats infact assigning the (undefined?) value even to variable num. Try this instead:

 if (num % 2 == 0) {

And instead checking for odd in separate if you could simply use } else { - there is no third case for integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM