试图哨兵循环这个程序

时间:2010-06-07 00:58:38

标签: java loops

  switch ( choice )
    {
       case '+':
          System.out.printf( "The answer is: %1$.4f.\n", first + second );
          break;
       case '-':
          System.out.printf( "The answer is: %1$.4f.\n", first - second );
          break;
       case '*':
          System.out.printf( "The answer is: %1$.4f.\n", first * second );
          break;
       case '/':
          if( second != 0 )
            System.out.printf( "The answer is: %1$.4f.\n", first / second );
          else
            System.out.println( "Can't divide by zero." );
          break;
       default :
          System.out.println( "You have entered an invalid operation.  Try again." );
          break;
    }

2 个答案:

答案 0 :(得分:2)

您可以使用return;语句终止函数

例如:

case 'x':
    return;

您还需要将其全部包装在while(true) { ... }中以使其永久循环(直到return;

答案 1 :(得分:2)

while (true)
{
    System.out.println("What type of Employee? Enter 'o' for Office " +
    "Clerical, 'f' for Factory, or 's' for Saleperson.  Enter 'x' to exit." );  
    String response= inp.nextLine().toLowerCase();

    // validate input, do you switch statement, return; on x     
}