2015-12-08 116 views
0

我怎樣才能得到下面的代碼重複input(),直到輸入一個數字並同時告訴用戶輸入了什麼類型的變量,是字符串,double或整數,如果滿足條件打印成功消息?重複一個方法,直到條件得到滿足

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

} 
+3

提示:使用循環。 –

+0

http://stackoverflow.com/questions/3133770/how-to-find-out-if-the-value-contained-in-a-string-is-double-or-not – akgaur

回答

0

這裏有一個註釋過的例子:

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; 
    } 
} 
+0

謝謝... ...它的工作原理! – sImAnTiCs

相關問題