【问题标题】:Do while loop meeting one of 2 conditions执行 while 循环满足 2 个条件之一
【发布时间】:2015-04-14 15:03:38
【问题描述】:

我正在尝试使用 do while 循环来确定用户是否希望将狗或猫签入 Java 中的犬舍系统。这个想法是他们在提示时输入“狗”或“猫”,任何输入都会导致错误,并且会再次提示他们输入文件名。

如果已经输入了“cat”或“dog”,那么等效文件将分配给程序(dogs.txt 或cats.txt),然后系统将运行并将该数据加载到程序中。

以下是当前变量:

private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";

以及导致问题的方法:

private KennelDemo() {
    scan = new Scanner(System.in);

    boolean fileNotCorrect = false;

    System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
    System.out.println("Dog");
    System.out.println("Cat");  
    tempFileName = scan.next();

    do {
        tempFileName.equals("dog");
        filename = dogsFile;
        fileNotCorrect = true;

        /*tempFileName.equals("cat");
        filename = catsFile;
        fileNotCorrect = true;*/
    }
        while(fileNotCorrect = false);
        System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");

这是运行代码时打印的内容:

**********HELLO***********
Which animal are you looking to check into the kennel?: 
Dog
Cat
cat
That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.
Using file dogs.txt

不管输入什么,它都会给程序分配一个文件,然后继续加载程序。

我尝试使用 catch { 但由于某种原因它不起作用,有人可以提供任何帮助吗?

谢谢!

【问题讨论】:

  • tempFileName.equals("dog"); 是一个比较;返回一个布尔值(真/假)。也许你想在它周围加上一个 if ( xxx) ?换句话说:您要研究的概念是“使用带有 if 的条件”。
  • 你没有 if 语句,tempFileName.equals("dog"); 只是返回一个布尔值,但你什么也没做。
  • 一个你的问题就在这里:while(fileNotCorrect = false)。那是一个任务,而不是一个比较。你所拥有的基本上是while(false)。使用== 进行比较。

标签: java while-loop


【解决方案1】:

do-while 不是这样工作的。你甚至没有检查。

使用这个:

 do {
    System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
    System.out.println("Dog");
    System.out.println("Cat");  
    tempFileName = scan.next();
    if(tempFileName.equals("dog") || tempFileName.equals("cat"))
    { 
       filename = tempFileName.equals("dog") ? dogsFile : catsFile;
       fileNotCorrect = true;
    }else{
      System.out.println("That is not a valid filename, please enter either 'dog' or 'cat' in lowercase.");
    }
}
    while(!fileNotCorrect);

【讨论】:

  • 非常感谢 Murat,这很有效。您介意简要解释一下为什么这是有效的,而不是我发布的内容,以便我能完全理解吗?再次感谢!
  • @JayGould 您基本上从未检查过任何内容,而您的 while 条件是第一次迭代后中断的分配。首先,您需要检查输入是否等于狗或猫。如果失败了,你给出 else 语句,让用户重新做一遍。这是可行的,因为只要条件为真,while 条件就会一直触发,反之亦然。
猜你喜欢
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2017-03-04
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 2020-10-31
相关资源
最近更新 更多