从while循环内部返回值

时间:2018-04-17 09:28:45

标签: java while-loop return

是否有可能从while循环内部返回值?我需要返回名称值。这是我的代码:

 public static String askFileName() {
    Scanner scanner = new Scanner(System.in);

    boolean flag = true;
    while (flag) {
        System.out.print("Type a file name: ");
        String name = scanner.nextLine();
        File file = new File(name);
        try {
            Scanner scanner1 = new Scanner(file);
            break;

        } catch (FileNotFoundException e) {
            flag = true;
        }
        return null   // ???;
    } 
}

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试下面的内容

public static String askFileName() 
{
    Scanner scanner = new Scanner(System.in);
    String temp = null;

    boolean flag = true;
    while (flag)
    {
        System.out.print("Type a file name: ");
        String name = scanner.nextLine();
        File file = new File(name);
        try 
        {
            Scanner scanner1 = new Scanner(file);
            temp = name;
            flag = false;
        }
        catch (FileNotFoundException e)
        {
            flag = true;
            temp = null;
        }
    } 
     return temp; //return value here
}