2016-01-05 69 views
0

如何使用下面的代碼返回我的菜單選項? 程序給出輸出後,我該如何返回菜單?如何再次打印菜單

import java.util.*; 
import java.util.Scanner; 
public class Meme { 
    public static void main(String[] args) 
    { 
     Scanner inp= new Scanner(System.in); 
     int choose; 
     System.out.println("Enter your selection:\n1 for Addition\n2 for substraction \n3 for Multiplication\n4 for division"); 

     choose = inp.nextInt(); 

     int num1,num2; 
     int ans; 
     System.out.println("Enter first number:"); 
     num1 = inp.nextInt(); 
     System.out.println("Enter second number:"); 
     num2 = inp.nextInt(); 


     switch (choose){ 
     case 1: 
      System.out.println(add(num1,num2)); 
      break; 
     case 2: 
      System.out.println(sub(num1,num2)); 
      break;  
     case 3: 
      System.out.println(mult(num1,num2)); 
      break; 
     case 4: 
      System.out.println(div(num1,num2)); 
      break; 
      default: 
       System.out.println("Illigal Operation"); 


     } 



    } 
    public static int add(int x, int y) 
    { 
     int result = x + y; 
     return result; 

    } 
    public static int sub(int x, int y) 
    { 
     int result = x-y; 
     return result; 
    } 
    public static int mult(int x, int y) 
    { 
     int result = x*y; 
     return result; 
    } 
    public static int div(int x, int y) 
    { 
     int result = x/y; 
     return result; 
    } 

} 

程序給出輸出後,我該如何返回菜單?

+2

添加一個',而(真)'循環,在菜單中有一個退出條件。 – Atri

+0

究竟是什麼?像在代碼中一樣? – user3753437

回答

3

有一個while循環包裝菜單和switch語句。給菜單添加一個退出條件,如果用戶輸入一個特定的值然後返回。

上的這個東西線(我假設從用戶的退出信號的任何其他輸入,你可以改變它按您的需要):

public static void main(String[] args) { 
    Scanner inp = new Scanner(System.in); 
    int choose; 

    while (true) { 
     System.out.println(
       "Enter your selection:\n1 for Addition\n2 for substraction \n3 for Multiplication\n4 for division\nExit: Any other input"); 

     choose = inp.nextInt(); 

     int num1, num2; 
     int ans; 
     System.out.println("Enter first number:"); 
     num1 = inp.nextInt(); 
     System.out.println("Enter second number:"); 
     num2 = inp.nextInt(); 

     switch (choose) { 
     case 1: 
      System.out.println(add(num1, num2)); 
      break; 
     case 2: 
      System.out.println(sub(num1, num2)); 
      break; 
     case 3: 
      System.out.println(mult(num1, num2)); 
      break; 
     case 4: 
      System.out.println(div(num1, num2)); 
      break; 
     default: 
      return; 

     } 
    } 
}