简体   繁体   中英

How to make a menu re-appear in java

import java.util.*;
public class LabTest1
{
public static void main(String[] args) 
    {
        Scanner console = new Scanner(System.in);
        double Choice1;
        double Choice2;
        int MenuChoice;
        System.out.print("Please enter the length: ");
        Choice1 = console.nextDouble();

        System.out.print("Please enter the width: ");
        Choice2 = console.nextDouble();

        System.out.println("=============================");
        System.out.println("|   MENU SELECTION          |");
        System.out.println("=============================");
        System.out.println("| Options:                  |");
        System.out.println("| 1. Calculate the area     |");
        System.out.println("| 2. Calculate the perimeter|");
        System.out.println("| 3. Exit                   |");
        System.out.println("=============================");
        MenuChoice = console.nextInt();
        System.out.print(" Select option: ");

    switch (MenuChoice)
    {
    case 1:
        System.out.println("Calculate the area selected");   
        System.out.println(Choice1 * Choice2);
        break;
    case 2:
      System.out.println(" Calculate the perimeter selected");  
      System.out.println(2*(Choice1 + Choice2));
      break;
    case 3:
        System.out.println("Exit selected");
        System.out.println(Choice1 + Choice2);
        break;

    default:
        System.out.println("Invalid selection");
        break; 
    }

    }
}

I need to make it so if the values are equal it should display a message saying that the values represent a square and allow the user to re-enter the values untill appropriate vlaues are entered ( yes i know a square is a rectangle)

Use the following pattern to ask for input, reject invalid input and loop:

boolean isValidInput = false;
[print prompt for input]
while (!isValidInput) {
   input = ...
   if (input is not valid) {
       print [invalid input, what is right form]
   } else {
       isValidInput = true;
   }
 }

By the way, you should use the minimum text possible. Print the request and what you are doing once, and the prompt for bad input each time they enter wrong information.

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