0

how can i get the following code to repeat input() until a numeric is entered and at the same time tell the user what type of of variable was entered,be it string,double or integer and if conditions are met prints out a success message?

package returnin;

import java.util.*;

public class trycatch {
public static void main(String[]args){
 String chck=input();
    String passed =check(chck);
    System.out.println("If you see this message it means that you passed the test");
}
static String input(){
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter a value");
    String var=sc.nextLine();

    return var;
}
static String check(String a){
    double d = Double.valueOf(a);
        if (d==(int)d){
        System.out.println( "integer "+(int) d);

        }
        else {
        System.out.println(" double "+d);
        }


        return a;
}

}
sImAnTiCs
  • 13
  • 2
  • http://stackoverflow.com/questions/3133770/how-to-find-out-if-the-value-contained-in-a-string-is-double-or-not – akgaur Dec 08 '15 at 12:30

1 Answers1

0

Here's a commented example:

package returnin;

import java.util.*;

public class trycatch {
    public static void main(String[] args) {
        // Don't recreate Scanner inside input method.
        Scanner sc = new Scanner(System.in);

        // Read once
        String chck = input(sc);

        // Loop until check is okay
        while (!check(chck)) {
            // read next
            chck = input(sc);
        }
        System.out.println("If you see this message it means that you passed the test");
    }

    static String input(Scanner sc) {
        System.out.println("Enter a value");
        return sc.nextLine();
    }

    static boolean check(String a) {
        try {
            // Try parsing as an Integer
            Integer.parseInt(a);
            System.out.println("You entered an Integer");
            return true;
        } catch (NumberFormatException nfe) {
            // Not an Integer
        }
        try {
            // Try parsing as a long
            Long.parseLong(a);
            System.out.println("You entered a Long");
            return true;
        } catch (NumberFormatException nfe) {
            // Not an Integer
        }
        try {
            // Try parsing as a double
            Double.parseDouble(a);
            System.out.println("You entered a Double");
            return true;
        } catch (NumberFormatException nfe) {
            // Not a Double
        }
        System.out.println("You entered a String.");
        return false;
    }
}
Jan
  • 13,738
  • 3
  • 30
  • 55