简体   繁体   中英

how can i run a set of code based on user input

I want to have a program that asks the user for an input of either yes or no. if no, it does nothing, but if it is a yes, it will run the following code.

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GettingCurrentDate {

    public static void main(String[] args) {

        //getting current date and time using Date class
        DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
        Date dateobj = new Date();
        System.out.println(df.format(dateobj));

        /*
         * getting current date time using calendar class
         * 
         * An Alternative of above
         */
        Calendar calobj = Calendar.getInstance();

        System.out.println(df.format(calobj.getTime()));
    }
}

Please review documentation for how to receive use input. I think this gives a succinct and basic explanation: Accepting Input from a User

Another user also provided a good link to review.

You need to combine this with an "if" statement: Java If... Else

A simple example based off the code your provided:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class GettingCurrentDate {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("Print current date? (yes/no)");

        String input = in.nextLine();


        if (input.equalsIgnoreCase("yes")){
            DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
            Date dateobj = new Date();
            System.out.println(df.format(dateobj));
        }
    }
}

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