简体   繁体   中英

Java:Do-while Loop, Even number then trying again

I can loop simply but it is hard for me to do even and odd numbers only. I want it like these for example:

Enter your number: 20

2 4 6 8 10 12 14 16 18 20

Do you want to do it again? Yes/No?

My code:

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    String c = null;
    do {
        int i;
        System.out.println("Enter a Number:");
        int n = input.nextInt();

        for(i=1; i<n; i++) {
            System.out.println(i);
            if(n%2==0) {
                System.out.println(i + " " );

            }
            System.out.println("Try Again? Y/N");
            c = input.next();   

        }
    }while(c.equalsIgnoreCase("y"));
}

Your code is saying if (n%2 == 0) but the loop iterates over i . This n will never change in each loop.

It's probably not the only problem in your code, but certainly you should be looking at what i does in the loop instead of n on that line.

You need to check i % 2 == 0 instead of n % 2 == 0 .

Demo:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String c = null;
        do {
            System.out.print("Enter a Number: ");
            int n = input.nextInt();

            for (int i = 1; i <= n; i++) {
                if (i % 2 == 0) {
                    System.out.print(i + " ");
                }
            }

            System.out.print("\nTry Again? Y/N: ");
            c = input.next();
        } while (c.equalsIgnoreCase("y"));
    }
}

A sample run:

Enter a Number: 20
2 4 6 8 10 12 14 16 18 20 
Try Again? Y/N: y
Enter a Number: 25
2 4 6 8 10 12 14 16 18 20 22 24 
Try Again? Y/N: n

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