首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何验证我的Java程序中的输入,并为用户添加重新运行或退出该程序的选项?

如何验证我的Java程序中的输入,并为用户添加重新运行或退出该程序的选项?
EN

Stack Overflow用户
提问于 2022-03-22 10:43:02
回答 3查看 601关注 0票数 2

因此,我在CISP 1类中有一个任务,要求我创建一个程序,根据5家不同的商店的销售额,显示由星号组成的条形图。我已经创建了一个基,但是我仍然希望添加一个循环来验证来自用户的输入(即当用户试图输入一个负数时抛出一个错误),并且我想添加运行程序或退出它的选项。我只是有点不知所措,所以我想我应该在这个网站上问一问。我知道很多代码可以用数组来简化,但是我们还没有开始研究--所以我害怕弄一些我不完全理解的东西。下面是我的代码:

代码语言:javascript
复制
import java.util.Scanner;

public class BarChart 

{
    public static void main(String[] args)

    {
        int store1, store2, store3, store4, store5;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("This program will display a bar chart " + 
        " comprised of astericks based on five different stores' " +
        "sales. 1 asterick = $100 in sales.");

        System.out.print("Enter today's sales for store 1: ");
        store1 = keyboard.nextInt();

        System.out.print("Enter today's sales for store 2: ");
        store2 = keyboard.nextInt();

        System.out.print("Enter today's sales for store 3: ");
        store3 = keyboard.nextInt();

        System.out.print("Enter today's sales for store 4: ");
        store4 = keyboard.nextInt();

        System.out.print("Enter today's sales for store 5: ");
        store5 = keyboard.nextInt();

        System.out.println("Sales \t Bar Chart");
        System.out.println("----- \t ---------");

        System.out.print("\nStore 1: ");        
        
        for (int num = 0; num < store1; num += 100)
        {
            System.out.print("*");
            
        }

        System.out.print("\nStore 2: ");
        for (int num = 0; num < store2; num += 100)
        {
            System.out.print("*");
        }

        System.out.print("\nStore 3: ");
        for (int num = 0; num < store3; num += 100)
        {
            System.out.print("*");
        }

        System.out.print("\nStore 4: ");
        for (int num = 0; num < store4; num += 100)
        {
            System.out.print("*");
        }

        System.out.print("\nStore 5: ");
        for (int num = 0; num < store5; num += 100)
        {
            System.out.print("*");
        }

    }
    
}

每次用户被要求输入销售金额时,我都尝试添加if语句,但这是行不通的。

EN

回答 3

Stack Overflow用户

发布于 2022-03-22 11:03:23

代码语言:javascript
复制
 Scanner keyboard = new Scanner(System.in); // initialize scanner  
 while (true) {  // infinite loop starts      
      <Do something...> // here you can do the things you need to do (e.g., change variables or record input)
      if (condition) { // condition for exiting the loop (e.g., input of positive number)
        break; // exiting infinite loop
      } // end of IF statement
    } // end of WHILE statement

You can use it as separate method and validate each input. It will not let the user to proceed until the valid value will be inputted.
票数 0
EN

Stack Overflow用户

发布于 2022-04-03 01:34:52

我仍然希望添加一个循环来验证来自用户的输入(即当用户尝试输入一个负数时抛出一个错误)。

下面是一个快速示例,演示如何再次询问输入无效编号时的问题:

代码语言:javascript
复制
do {
    System.out.print("Enter today's sales for store 1: ");
    store1 = keyboard.nextInt();
    if (store<0) {
        System.out.println("Sales must be non-negative!");
    }
while (store<0);

,我想添加运行或退出程序的选项。

这与上面的do { ... } while( ... );类似,只是将整个程序从Scanner行下面放到do循环的主体中。然后,您只需在底部询问他们是否希望重新开始,并适当地在while部分中编写条件语句。

票数 0
EN

Stack Overflow用户

发布于 2022-04-03 01:39:23

请花时间读一遍

问题的解决办法

并发循环

您要寻找的是一个while循环,这个答案提示您,但是您可以指定是强制用户重试,还是中断程序并抛出一个错误。

如果希望使用户重试,而不抛出导致程序中断的错误,可能会在用户每次输入负数时使用重试消息,则可以使用do-while循环。do-while循环将执行为“做这个然后检查”,而不是while循环“检查而不是这样做”(这样可以确保代码更加简洁)。do-while循环版本:

代码语言:javascript
复制
int input;  // Declare the variable to be initialized inside the do {} block.
int storeSales;                      // You can just relax and declare here.
do {                                 // This is the start of the do-while loop
    System.out.print("...");         // Your prompt goes here
    storeSales = scanner.nextInt();  // Grabbing input from the user
    if (storeSales < 0) {            // Checking if the input is smaller than 0
        System.out.print("...");     // Your message when input is invalid
    }
} while (storeSales < 0);            // The condition goes here

这种情况下的do-while循环的警告是因为在while循环中,do块总是至少要执行一次的条件,需要一个变量,即不是先初始化,而是在循环本身E 218中初始化的E 117初始化一个“用户输入”变量,但是给它一个“使语句工作的值”的值,使代码变得笨拙和肮脏。

同时循环

while循环版本如下所示:

代码语言:javascript
复制
int storeSales = -1;  // You have to initialize first here, since the while is checked first.
while (storeSales < 0) {  // Awkward!
    System.out.print("");           // Your prompt goes here
    storeSales = scanner.nextInt(); // Grabbing input from the user
    if (storeSales < 0) {           // Checking if the input is smaller than 0
        System.out.print("");       // Your message when input is invalid
    }
}

例外情况

如果相反,当输入无效(小于0)时,您希望中断程序:引入throw语句:尝试以下代码:

代码语言:javascript
复制
public class BarChart {
    public static void main(String[] args) {
        System.out.println(5 / 0);
    }
}

你要冲我吼:WTF is this, you're making a program that throws ArithmeticException runtime exception! Division by 0 doesn't make sense!

好吧,这就是重点。Java中的Exceptions是在运行时发生的,因为一些与语法无关的条件,比如String x = 0等明显的错误,这就是您要寻找的异常。要抛出类似于上面的示例这样的错误,请使用throw语句,不要使用循环:

代码语言:javascript
复制
int storeSales = scanner.nextInt();
if (storeSales < 0) {
    // Since the exception is related to math, you can use something like ArithmeticException. Your choice though.
    throw new ArithmeticException();  // An exception is also an object, so you initialize it that way.
}

警告,Java一开始并不期望异常,所以您必须声明您的方法抛出异常。甚至是main()。当您调用其他方法(也有异常)时,要么使用try-catch块处理它们,要么保留它并将异常添加到方法定义中。但我想这是另一天的事了。

一般改进

您正在做相同的事情您可以使用for循环。除非您的名字必须是唯一的,并且必须单独声明(我不知道,您的名字实际上是store1store2store3等等)您可以在for循环的每一次迭代中使用一个通用的、重新初始化的变量名。

您还可以扫描用户输入的关于的多少存储(而不是硬编码5)来显示数据,使程序完全软编码和动态(分配可能不需要这个,根据需要重构代码)。

下面的代码将抓取用户输入,然后在之后立即输出它。现在我看了您的解决方案,也许定义单独的变量而不是将输入放在数组中是正确的,因为您希望所有的输入一次,然后立即打印的所有输入。事情是这样的:

代码语言:javascript
复制
// You'd want to reformat the code to your preference.
import java.util.Scanner;
public class BarChart {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int storeCount = scanner.nextInt();
        for (int i = 0; i < storeCount; i++) {  // A loop that repeats 5 times.
            // Choose one of the three solutions above and insert them here, I choose the do-while since it's the cleanest
            int storeSales;
            do {
                // You can "concatenate" strings (numbers becomes themselves but in text)
                System.out.print("Enter today's sales for store " + (i + 1) + ": ");
                storeSales = scanner.nextInt();
                if (storeSales < 0) {
                    System.out.print("Sales cannot be negative, please try again");
                }
            } while (storeSales < 0);
            // Now that the storeSales value has been definitely initialized (or you chose the exceptions solution, I don't blame you) the printing goes here.
            System.out.println("Store " + (i + 1) + "'s sales:");
            for (int j = 0; j < storeSales; j += 100) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

否则,与代码无关,因为如果不使用数组,最好的方法是定义单独的变量,然后使用一两个方法(带有名称的可重用代码)来完成输入和打印工作,从而使代码更简洁、更少重复。

最后,只需选择三种解决方案之一,并将它们应用于每个变量。您的代码非常好(如果是这样的话)。干杯!

哦,天哪,有人读到帖子的结尾,我爱你

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71570670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档