如何在do while循环中执行y / n选项?

时间:2013-11-16 14:57:39

标签: java

我想知道是否有人能引导我朝正确的方向发展,我刚开始使用java并且我遇到字符串验证问题,我想在这里做的是为每个孩子重复循环,重复循环你想要每个孩子的书籍,然后在没有孩子的时候退出。我正在努力与y / n选项以及如何使它只有这两个选项有效,否则用户将被显示无效选项再试一次。任何帮助将不胜感激!真的难倒在这里!

     int childcounter=1;
    do{
      System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
      cfn=k.next();
      System.out.print("What is "+cfn+"'s age?");
      cage=k.nextInt();
      System.out.println();
      do {
      System.out.print("What is the title of the book that " +cfn+ "would like?");
      btitle=k.next();      
      System.out.print("Price of '"+btitle+"' ?");
      costbook=k.nextDouble();  
      System.out.println();
      System.out.print("Do you want to finish? y/n ");
      finished=k.next();
    }
    while(finished.equals("N") || (finished.equals("n")));
      childcounter++;
    }
while (childcounter <= nochild); }

2 个答案:

答案 0 :(得分:0)

下面

System.out.print("Do you want to finish? y/n ");
String finished = k.next();

添加

while (!java.util.Arrays.asList("y","n","Y","N").contains(finished)) {
    System.out.println(" Invalid option. Try again.");
    System.out.print("Do you want to finish? y/n ");
    finished = k.next();
}

答案 1 :(得分:0)

使用equalsIgnoreCase('n')可以减少必须输入的代码量。

改为使用它。

while (finished.equalsIgnoreCase('n')
{

//method body here in the style that @halfbit suggested.
childcounter++;
}