gpt4 book ai didi

java - 当输入的年龄与数字不同时,我需要返回字符串

转载 作者:行者123 更新时间:2023-12-02 00:16:24 25 4
gpt4 key购买 nike

  1. 您好,我附上了关于您的问题的解决方案,我评论了有关代码的不同部分。有两个函数,其中信号是数字数据或年龄类别。 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

    import java.util.Scanner;

    public class main {

    public static void main(String[] args) {
    System.out.print("Type your age: ");

    Scanner sc = new Scanner(System.in);
    //Save var String
    String ageStr = sc.nextLine();

    String notify="Not an age.";
    //Evaluate the age if we typify a number.
    if (isNumeric(ageStr)==true) {
    int age = Integer.parseInt(ageStr);
    notify = myAge(age);
    }

    //Notification about your Age
    System.out.println(notify);
    }
    //Method about Age
    public static String myAge(int age) {

    if (age >= 18) {
    return "Over 18 or equals 18";
    }
    else if (age == 0) {
    return "0 age?";
    }
    else if (age <= 18) {
    return "Under 18";
    }
    return null;
    }
    //Method is numeric?
    public static boolean isNumeric(final String str) {

    if (str == null || str.length() == 0) {
    return false;
    }

    for (char c : str.toCharArray()) {
    if (!Character.isDigit(c)) {
    return false;
    }
    }

    return true;

    }

    }

希望可以帮到你

问候

<小时/>

最佳答案

正如您所说,您当前会收到一个InputMismatchException。您可以简单地捕获它并返回您想要的值。

Doc for Scanner.nextInt()链接为 arcadeblast77

public class Age {

public String AgeFunction() {

Scanner sc = new Scanner(System.in);

// User type your age
try {
System.out.print("Type your age: ");
int age = sc.nextInt();

if (age >= 18) {
return "Over 18 or equals 18";
}

else if (age == 0) {
return "0 age?";
}

else if (age <= 18) {
return "Under 18";
}

// If what was typped be different int, return string


} catch (InputMismatchException exception) {
return "Not an age.";
}

}

}

关于java - 当输入的年龄与数字不同时,我需要返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58087511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com