首页 > 解决方案 > 如何在此特定实例中使用 Do-While 循环(程序在 y/n 之前完成)Java

问题描述

我正在做一个需要继续提问的实验室,但无论我做什么,程序总是在接受答案之前停止。这是我的主要方法:

import java.util.Scanner;
import static java.lang.System.*;

public class Lab03b
{
public static void main( String args[] )
{
    Scanner scan = new Scanner(in);

    boolean ans = true;
    do{
        out.println("Enter the word to display:: ");
        String word = scan.nextLine();
        out.println("Enter the number of times to display:: ");
        int times = scan.nextInt();

        out.println("Do you wish to continue? (y/n):: ");
        String choice = scan.nextLine();

        WordPrinter.printWord(word,times);



        if (choice == "y" || choice == "Y")
        { ans = true;
        }
        else
        {
            ans = false;
        }
    } while(ans == true);

}
}

它引用了另一个类,该类通过基本循环打印出一个单词 x 次。任何帮助表示赞赏。

标签: javajava.util.scanner

解决方案


推荐阅读