簡體   English   中英

重復方法直到滿足條件

[英]Repeating a method until conditions are met

我如何獲得以下代碼來重復input()直到輸入了數字,同時告訴用戶輸入了什么類型的變量,可以是字符串,雙精度或整數,並且如果滿足條件,則會打印出成功消息?

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

}

這是一個有注釋的示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM