2011-06-08 100 views
0

如何在用户输入0时结束do-while循环?结束这个do-while循环?

该计划将继续执行,如果用户输入F,G,H和J 如果用户输入0

import java.util.Scanner; 

public class P4Q5 { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 


     Scanner sc = new Scanner(System.in); 
     System.out.println("\nMain Menu: \n" + 
       "Enter 0 to exit program\n" + 
       "Enter F to display Faith\n" + 
       "Enter G to display Grace\n" + 
       "Enter H to display Hope\n" + 
       "Enter J to display Joy\n"); 



     do { 
      System.out.print("Enter your choice:"); 
       String s = sc.nextLine(); 
      char ch = s.charAt(0); 
      if ((ch == 'F')) { 
       System.out.println("\nFaith\n"); 
      } 

      else if ((ch == 'G')) { 
       System.out.println("\nGrace\n"); 
      } 

      else if ((ch == 'H')) { 
       System.out.println("\nHope\n"); 
      } 

      else if ((ch == 'J')) { 
       System.out.println("\nJoy\n"); 
      } 



      else { 
       System.out.println("\nWrong option entered!!\n"); 
      } 

     } while (ch == 'O'); 

       // TODO code application logic here 
    } 

} 

回答

1

试试这个在你做方案将退出,而:

if(ch == '0') break; 
+0

如果你能避免它,破坏是一个坏习惯。 – bitmask 2011-06-08 09:59:44

+0

感谢它的工作! :DD – user788949 2011-06-08 10:55:03

+0

@ user788949:当输入不是“O”时,你的循环总是会中断,那么可疑的while-condition'ch =='O''怎么办?我的意思是,如果它仍然被你的规格所破坏,它怎么能起作用? – 2011-06-08 12:05:11

2

while (ch != '0')而不是while (ch == 'O')?请注意0​​和O之间的区别?

+0

或者你可以使用while(true)和break ch == 0,但这也是正确的 – RubenHerman 2011-06-08 10:00:50

1

试试这个:

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
Scanner sc = new Scanner(System.in); 
System.out.println("\nMain Menu: \n" + 
     "Enter 0 to exit program\n" + 
     "Enter F to display Faith\n" + 
     "Enter G to display Grace\n" + 
     "Enter H to display Hope\n" + 
     "Enter J to display Joy\n"); 



do { 
    System.out.print("Enter your choice:"); 
     String s = sc.nextLine(); 
    char ch = s.charAt(0); 
    if ((ch == 'F')) { 
     System.out.println("\nFaith\n"); 
    } 

    else if ((ch == 'G')) { 
     System.out.println("\nGrace\n"); 
    } 

    else if ((ch == 'H')) { 
     System.out.println("\nHope\n"); 
    } 

    else if ((ch == 'J')) { 
     System.out.println("\nJoy\n"); 
    } 

    else if ((ch == 'O')) { 
     System.exit(); 
    } 

    else { 
     System.out.println("\nWrong option entered!!\n"); 
    } 

} while (ch == 'F' || ch == 'G' || ch == 'H' || ch == 'J' || ch == 'O'); 

     // TODO code application logic here 

}

要退出程序,你需要做的System.exit()的

要退出循环不作为@bitmask说

0

我会用一个布尔变量,如果你输入0布尔值变为true,然后检查布尔值...

boolean bool = false; 
    do { 
     ... 

     if(input == '0') 
      bool=true; 
    } while (!bool); 

哦,之前我忘了,我也会做一个输入之前的做,而一个在循环结束。像这样,你的整个代码在你点击后不会再运行。

+0

除了“bool”不是一个好名字。最好使用像“done”或“exitRequested”这样的描述性内容。 – 2014-08-31 12:48:37