从“if”重复一个方法,直到输入要返回的正确值

时间:2015-12-21 13:52:55

标签: java return java.util.scanner

当我在工作中无所事事时,我正在努力学习Java的基础知识,并且我想要输入。这就是我现在所拥有的:

import java.util.Scanner;
public class Input {
    private static Scanner input;
    public static void main(String [] args){
        String name = (askName());
        double age = (askAge());
        System.out.println("Your name is " + name + " and your age is " + age);
    }
static String askName(){
    System.out.print("What is your name?");
    input = new Scanner(System.in);
    //listens for strings
    String name = input.next();
    return name;
}
static double askAge(){
    System.out.print("What is your age?");
    input = new Scanner(System.in);
    //listens for doubles
    double age = input.nextDouble();
    if (input.hasNextDouble()){
        return age;
    } else {
        System.out.println("Please insert a number:");
        askAge();}
}
}

这就是我得到的:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    This method must return a result of type double

    at Input.askAge(Input.java:16)
    at Input.main(Input.java:6)

我该怎么做才能强制用户输入一个整数(也就是说,如何让该方法重复出现,直到它获得一个可以返回的int?)

4 个答案:

答案 0 :(得分:2)

返回递归调用的值:

System.out.println("Please insert a number:");
return askAge();

然而:在这里使用循环而不是递归会更好,因为如果你继续输入无效值,你最终可以获得StackOverflowError

答案 1 :(得分:1)

如果条件用于决策而不是用于循环。 使用while循环,当你得到正确的值时打破循环。 我正在连接一个sudo代码。

while(true){
if (input.hasNextDouble()){
        //Assign value to a variable ;
        //Break loop
    } else {
        //Re ask question 
        System.out.println("Please insert a number:");
       }

}

示例link为您提供帮助。

您获得的异常是因为您没有从else部分的askAge()返回任何值。

答案 2 :(得分:0)

我宁愿这样做:

public static void main(String [] args){
    Scanner sc = new Scanner(System.in);
    String name = getString(sc, "What is your name? ");
    int age = getInt(sc, "What is your age? ");
    System.out.println("Your name is " + name + " and your age is " + age);
}


/* You increase the performance when using an already existing single      
scanner multiple times for different reasons (to get a name, first name, 
second name, age, etc.), instead of making a new Scanner each time */

public static String getString(Scanner sc, String message) {
    System.out.print(message);
    return sc.nextLine();
}

public static int getInt(Scanner sc, String message) {
    System.out.print(message);
    if (sc.hasNextInt()) {
        return sc.nextInt();
    } else {
        sc.next(); // required to skip the current input
        return getInt(sc, "Please insert a number: ");
    }
}

答案 3 :(得分:-1)

请改变你的方法,

actionButton('updateButton',label = "Filter")