user8195995
user8195995

Reputation:

How can I output a chosen option of the users choice in my program?

My program is going to present the user with a box and give them multiple options. As a result, they will have to input an integer which represents which step they wish to proceed with. I'm wondering how I can output what step they chose within the program. Would I need to use a for statement for this?

Box example picture

import java.util.Scanner;
public class testing {
    public static void main (String []args){ 
        Scanner input = new Scanner(System.in);
        String coursename;
        String option1 = "BTEC 90 Credit Diploma Grade"; 
        String option2 = "BTEC Extended Diploma Grade"; 
        String option3 = "Functional Skills"; 
        String option4 = "Help"; //assigning text to variable
        String option5 = "Exit"; //assigning text to variable
        String outline = "+-----------------------------------------------+";

        System.out.println(outline);

        System.out.println("| |1|         "+option1+ "      |");  
        System.out.println("| |2|         "+option2+ "       |");  
        System.out.println("| |3|         "+option3+ "                 |"); 
        System.out.println("| |4|         "+option4+ "                              |");   
        System.out.println("| |5|         "+option5+ "                              |");  

        System.out.println(outline);
        coursename = two.next();
        System.out.println("Answer entered was " + ?); //? represents not sure what to put. 

    }
}   

Upvotes: 0

Views: 102

Answers (2)

Jiri Tousek
Jiri Tousek

Reputation: 12440

Either a for loop, or store the option texts in a Map indexed by the key pressed to choose it.

If you put them into a LinkedHashMap, you could also print them in a for loop instead of doing so manually for each option.

Map<Integer, String> options = new LinkedHashMap<>();
options.put(1, "BTEC 90 Credit Diploma Grade");
...

for (Entry<Integer, String> entry : options.entrySet()) {
    System.out.println(
        "| |" + entry.getKey().toString() + "|         "
        + entry.getValue() + repeat(" ", 40 - entry.getValue().length())
        + "|"
    );
}

...

Integer choice = input.nextInt();
System.out.println("Answer entered was " + options.get(choice));

Upvotes: 0

Neil Locketz
Neil Locketz

Reputation: 4318

Scanner#nextInt() will do the trick.

To get the number just do:

int num = input.nextInt();

Once you have the number you can use

if (num == 1) { System.out.println(option1); }

For option one. Just continue for all your options. No loops are necessary since you know the number that corresponds to each option.

Upvotes: 1

Related Questions