在Java中创建动态do-while语句?

时间:2018-04-07 12:44:35

标签: java function dynamic do-while

我一直想知道,是否可以在Java中创建动态do-while语句(使用函数/方法)?

我一直在努力,并且让这种“半自动”功能起作用:

import java.util.*;

public class Test{
    Scanner inp = new Scanner(System.in);

    Test(){
        String name = "", any = "";
        int num = 0;
        System.out.println("Static 1");

        //the 'semi-automatic' do while sample
        doWhile("Input name (String): ", name, 3, 10);
        doWhile("Input number (Integer): ", num, 1, 17);

        //another do while statement; I know this won't work
        doWhile("Input anything but numeric: ", any, !any.matches("[A-Za-z]+"));

    }
    public static void main(String[] args){
        new Test();
    }


    void doWhile(String a, String b, boolean c){
        do{
            System.out.print(a);
            b = inp.nextLine();
        } while(c);
    }

    //do-while string
    void doWhile(String a, String b, int c, int d){
        do{
            System.out.print(a);
            b = inp.nextLine();

        } while(b.length() < c || b.length() > d);

    }

    //do-while int
    void doWhile(String a, int b, int c, int d){
        do{
            System.out.print(a);
            try{
                b = inp.nextInt();
            } catch(Exception e){
                System.out.println("Please input accordingly");
            }
            inp.nextLine();
        } while(b < c || b > d);
    }

}

我知道问题必须来自'while'值,我已经用尽了如何让它完全动态化。任何想法(或可能替代)?

0 个答案:

没有答案