0

I've been wondering for a moment, is it possible to create a dynamic do-while statement in Java (with function/method)?

I've been working around, and have this 'semi-automatic' function work:

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);
    }

}

I know that the problem must be came from 'while' value, which I have ran out of ideas on how to make it fully dynamic. Any ideas (or perhaps alternative)?

Gregory
  • 1
  • 3
  • I mean to create a do-while statement through the use of function, so I don't have to write down the whole do-while line for another loop @Carcigenicate – Gregory Apr 07 '18 at 12:49
  • Aw snap, I know this going to lead me somewhere a bit expertise :c Unfortunately I didn't yet learn on using the lambda expression – Gregory Apr 07 '18 at 13:11
  • I think I actually misunderstood your question. Do you just want to have 3 separate `do-while` functions, but only need to write an actual `do...while` only once? You're just looking to reduce the repetition of those 3 function definitions? – Carcigenicate Apr 07 '18 at 13:58
  • No problem, sometimes it happened, and yeah, that's what I've been looking for at this point – Gregory Apr 07 '18 at 14:20
  • There's no way I can think of that would lead to better code; those functions are already pretty bare-bones. If the functions were more complicated, maybe, but any solution I can think of would add enough bloat that it wouldn't be worth it. – Carcigenicate Apr 07 '18 at 15:19

0 Answers0