简体   繁体   English

Java-如果用户输入无效的输入,如何返回异常?

[英]Java - How would I return an exception if the user enters a invalid input?

I'm a complete beginner when it comes to coding. 关于编码,我是一个完整的初学者。 I'm currently taking a programming class at my local community college. 我目前正在当地社区大学上编程班。 We've been given an assignment to create a program that calculates the BMI (body mass index) of the user. 我们已被分配创建一个程序来计算用户的BMI(体重指数)。

I've managed to create the basis structure of the program, where the user inputs there weight and height and have it calculated into the BMI however, there is one criteria I'm struggling to create. 我设法创建了程序的基础结构,用户在此处输入了体重和身高,并将其计算到BMI中,但是,我正在努力创建一个标准。

In which is to display any invalid inputs of the following 在其中显示以下任何无效输入

  • Height is not less than 48 inches 高度不小于48英寸
  • height is not more than 80 inches 高度不超过80英寸
  • weight is not less than 75 Ibs 重量不少于75磅
  • weight is not more than 300 Ibs 重量不超过300磅

Example interactions 互动示例

Please enter your height in inches: 20 请输入您的身高(英寸):20
sorry, you have enter a height that is not valid 抱歉,您输入的高度无效

Please enter your height in inches: 62 请输入您的身高(英寸):62
Please enter your weight in pounds: x 请输入您的体重(磅):x
sorry, you did not enter a number in pounds 抱歉,您没有输入磅数


I've kinda have an idea, since people are suggesting to use the try, catch statement. 我有点主意,因为人们建议使用try,catch语句。 I've attempted but I can seem to figure it out. 我已经尝试过,但似乎可以弄清楚。

import java.util.*;
public class BMI {

    public static void main(String[ ] arg){

        // BMI calculator 
        Scanner keyboard = new Scanner ( System.in ); 
        final double BMI_CONVERSION = 703.0; // pounds/inches to kilograms/meters for BMI calculations 

        double bodyMassIndex; 
        double height = 0; 
        double weight = 0;
        String BMICategory = "";

        // user inputs 

        // inches
        System.out.print( "What's your height in inches? "); 
        height = keyboard.nextDouble();

        // Pounds
        System.out.print( "What's you weight in pounds? "); 
        weight = keyboard.nextDouble(); 

        // Calculate BMI 
        bodyMassIndex = weight * BMI_CONVERSION / (height * height); 
        if (bodyMassIndex < 18.5) 
        { 
            BMICategory = "considered at a underweight"; 
        } 
        else if (bodyMassIndex >= 18.5 && bodyMassIndex <= 25) 
        { 
            BMICategory = "considered at a optimal weight"; 
        } 
        else 
        { 
            BMICategory = "considered overweight"; 
        } 


        // output 
        System.out.println( "Your BMI is: " + bodyMassIndex + ", You are " +     BMICategory + ".");

    }
}

You need to reorganize your program if you want to use exceptions.Exception means you would have a try/catch block outside of function, that throws exception. 如果要使用异常,则需要重新组织程序.Exception意味着您将在函数之外有一个try / catch块,这会引发异常。

1) - Create class that would have necessary fileds for calculations, and calculate method. 1)-创建将具有用于计算的必要字段的类,并计算方法。

2) - Create class that would be responsive for the input cycle, with separate functions for each varialbe. 2)-创建对输入周期有响应的类,并为每个变量创建单独的函数。 This method should throw Exception if the value is invalid.Create master-function that will call all necessary functions to read data and will close it into try/catch block Like this 如果该值无效,则此方法应引发Exception.Create master函数将调用所有必要的函数以读取数据并将其关闭到try / catch块中

public BMI masterFunc(){

try{


    readFirst();

    readSecond();

    //etc....
    BMI obj = new BMI();
    //set you params to new created class BMI
    //and return it from func
    return obj;

}catch(Exception e){

    return null;

 }

}

Now you could put it in cycle in main like 现在您可以将其循环放置

BMI obj = null;

while(obj == null)
    BMI obj = ReaderClass.masterFunc();

Hope i could answer you question! 希望我能回答你的问题!

看看“ public void functionName() throws InvalidInputException ”。

First of all, putting your code on and asking for help is against website rules. 首先,放置代码并寻求帮助违反了网站规则。

Anyways, in your code you need to loop your input(while loop with value set as true would be the best bet), in this loop you check if the input is falling into your criteria. 无论如何,在您的代码中,您需要循环输入(而将值设置为true的循环将是最好的选择),在此循环中,您将检查输入是否符合条件。 If it is then you break out of the loop. 如果是,那么您就跳出了循环。

This way you can stick to your criteria and get the BMI at the end. 这样,您可以坚持自己的标准并最终获得BMI。

PS the concepts used here are looping and breaking out of a loop, you can check out some examples online for better understanding PS这里使用的概念是循环和突破循环,您可以在线查看一些示例以更好地理解

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 java 实验室中使用 While(用户输入无效输入) - Using While in java lab (User enters invalid input) 如果用户输入一个空格作为他们的输入,你会如何将其读为“ ”字符串? - If the user enters a blank space as their input, how would you read that as a “ ” string? 在用户在Java中输入空白行之前,我将如何进行此循环? - How would I make this loop until the user enters a blank line in java? 如果用户输入无效选项,则请求相同的输入 - Requesting the same input if user enters an invalid option 如果用户输入的是小数点后两位,如何返回无效值? 爪哇 - How can return invalid if user input is 2 decimal places? java 如果用户输入了无效密码,该如何编码? - If the user enters an invalid code how to code it? 如何验证用户是否在Java中输入整数或字母字符? - How can I verify that a user enters an integer or alphabetic character in Java? 如何验证用户在 java 中输入的数据 - how do I validate a data that user enters in java 如何为用户输入无效添加例外? 用户应输入名称,如果输入不是名称,则需要抛出异常 - How to add an exception to account for invalid user input? User should input a name and I need to throw an exception if input is not a name 当用户输入错误的字符或无效的输入数据时,如何显示“打印”错误? - How to display a “print” error when the user enters wrong character or invalid input data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM