用我的Do循环格式化问题

时间:2015-05-10 08:02:30

标签: java

我在尝试解决代码中的冗余时遇到了一些问题。我做循环检查以查看用户输入是否不等于“再见”如果它不等于再见那么它会完成所有预期的操作。但是当我得到“你还有什么想知道的东西”时我会卡住并且不知道如何再次运行该程序来调用解析文件()所以我不得不复制

     System.out.println("is there anything you want to know?");
        input = scanner.nextLine().toLowerCase();
        parseFile(input);

有没有办法让这个程序在不重复上述代码的情况下工作?          public static void getinput()抛出IOException {

    Scanner scanner = new Scanner(System.in);
    String input = null;
    /* End Initialization */

    System.out.println("Welcome ");
    System.out.println("What would you like to know?");

    do {
        System.out.print("> ");
        input = scanner.nextLine().toLowerCase();
        parseFile(input);

        System.out.println("is there anything you want to know?");
        input = scanner.nextLine().toLowerCase();
        parseFile(input);

    } while (!input.contains("bye")); 
    System.out.println("have a good day");

}

3 个答案:

答案 0 :(得分:0)

试试这个:

boolean flag=false;
do {
    if(!flag)
        System.out.print("> ");
    else
        System.out.println("is there anything you want to know?");

        input = scanner.nextLine().toLowerCase();
        parseFile(input);
        flag=!flag;
    } while (!input.contains("bye")); 

答案 1 :(得分:0)

你可以试试这个

public static void getinput() throws IOException {

    Scanner scanner = new Scanner(System.in);
    String input = null;
    /* End Initialization */

    System.out.println("Welcome ");
    System.out.println("What would you like to know?");

    for (;;) {
        System.out.print("> ");
        input = scanner.nextLine().toLowerCase();
        parseFile(input);

        if (input.equals("bye"))
            break;

        System.out.println("is there anything you want to know?");
        input = scanner.nextLine().toLowerCase();
        parseFile(input);
//might add another checker here
//if (input.equals("bye"))
        //  break;

    }
    System.out.println("have a good day");

}

答案 2 :(得分:0)

我建议您应该在循环外获得第一个输入,然后在循环开始时检查input是否包含"bye"然后进入循环。因此,这会将您的循环从do - while更改为while循环。我在下面说明:

System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();

while (!input.contains("bye")) {
    parseFile(input);

    System.out.println("is there anything you want to know?");
    input = scanner.nextLine().toLowerCase();
} ;