简体   繁体   English

如何检查整数或字符串,以及是否再次询问[Java]

[英]How to check for an integer or a string and if not ask again [Java]

There are a bunch of threads throughout the internet on this but I can't make heads or tails of any of them. 整个互联网上都有很多线程,但是我无法做出任何决定。

As an assignment for an intro to Java course we have been tasked with making a handful of different programs, we were then given them back and told to make them idiot proof. 作为Java课程入门的一项任务,我们被要求制作一些不同的程序,然后让我们将它们还给他们,并被告知要使它们成为白痴证明。

So for example, we have to use a program to determine what day of the week a random day of any random year will be, (ie Jan 1 2013 being a Tuesday) 因此,例如,我们必须使用一个程序来确定任何随机年份中的任意一天是星期几(例如,2013年1月1日为星期二)

I prompt for three things, Day, Year and Month, I want to make it so that if Day is contains a letter it sends back Invalid and prompts again. 我想输入三件事,即日,年和月,因此要使它包含在内,如果“日”包含一个字母,它将发回“无效”并再次提示。

Right now I have it set so that if day is an integer less than one or greater than 31 it asks again, so I don't have a problem with the range, just the NFE. 现在,我将其设置为,如果day是小于1或大于31的整数,它将再次询问,因此我对范围没有任何疑问,仅对NFE有问题。

I have heard that I should use a 我听说我应该使用

 Try
    {
    //...
    }
    catch{NumberFormatExcept nFE}

but I have no idea how to use that to re-prompt for what I an looking for 但我不知道如何使用它来提示我想要的东西

Here is a snippet of my code so far 到目前为止,这是我的代码的一部分

             System.out.print("Enter the day of the month (1-31): ");
             int d = UserInput.nextInt();

            do
            {
                if(d < 1 || d > 31)
                {
                    System.out.print("That day is invalid, please enter a day between 1 and 31");
                    d = UserInput.nextInt();
                }
            }while(d < 1 || d > 31);

I tried making da string and using Integer.parseInt(); 我尝试制作da字符串并使用Integer.parseInt(); but that would just parse a into 1, I want to so something like if d.hasNextInt(); 但这只是将a解析为1,我想像d.hasNextInt();这样。 continue, but if it hasNextString() reprompt. 继续,但是如果hasNextString()再次提示。

AKA AKA

    String d;
    d = UserInput.nextLine();
    int dVar = Integer.parseInt(d);

I can't just throw an exception because the objective is to not crash but just prompt again. 我不能仅仅抛出一个异常,因为目标是不崩溃而只是再次提示。

Consider creating a method for reading in a valid integer. 考虑创建一种读取有效整数的方法。 Pass this method the valid integer range. 将此方法传递给有效整数范围。 The method would attempt to read the value once and validate. 该方法将尝试一次读取值并进行验证。 If the method fails, return null , if it passes return the Integer . 如果该方法失败,则返回null ,如果通过则返回Integer Call this method in a do-while loop until you get a non-null Integer . do-while循环中调用此方法,直到获得非null的Integer为止。

It looks like you are using Scanner to get input. 您似乎正在使用Scanner获取输入。 (By the way, in Java, it is conventional for variables to start with lower-case letters). (顺便说一下,在Java中,变量通常以小写字母开头)。

If that's the case, if you attempt to scan an int when there isn't one in the input, an InputMismatchException will be thrown. 如果真是这样,如果您尝试在输入中没有int的情况下扫描int ,则会抛出InputMismatchException You avoid this by testing whether this will happen before you try to read the int . 通过尝试读取int 之前 测试是否会发生这种情况可以避免这种情况。

So, think about a loop structure like this: 因此,考虑这样的循环结构:

int d = 0;
while (true) {
  if (/* The input isn't an integer */) {
    /* Tell the user. */
    continue;
  }
  d = input.nextInt();
  if (/* The input is out of range */) {
    /* Tell the user. */
    continue;
  }
  ...
  /* When you've completed all of your tests and everything is okay, break. */
  break;
}

By the way, many months don't have 31 days. 顺便说一句,很多个月没有31天。

First off, you really shouldn't use exceptions for input validations. 首先,您确实不应在输入验证中使用异常。 Exceptions are for exceptional conditions ; 例外是特殊情况 ; things you don't expect to happen. 您不希望发生的事情。 Josh Bloch outlines this specifically in his excellent book Effective Java 乔什·布洛赫(Josh Bloch)在他的出色著作《 有效的Java》中专门概述了这一点。

As for your code, I would suggest using the hasNextInt() method combined with getting the input as an int and checking for the range you require as you've actually stated in your question. 至于您的代码,我建议结合使用hasNextInt()方法和将输入作为int并检查问题中实际指出的范围。

int d = 0;

while (d < 1 || d > 31)
{
    System.out.print("Enter the day of the month (1-31): ");
    if (userInput.hasNextInt())
    {
        int d = userInput.nextInt();

    }
    else
    {
        String s = userInput.next();
    }

    if(d < 1 || d > 31)
    {
        System.out.print("That day is invalid - ");
    }    

}

Are you familiar with the behavior of a try-catch statement? 您是否熟悉try-catch语句的行为?

try
{
   //do something that may throw an exception you can handle
}
catch(Exception ex)
{
   //If we enter this block, an exception was thrown from the try block's code

   //If you cannot fully handle the exception, you can rethrow it
   throw ex;
}
finally
{
   //This code ALWAYS executes, unless the program is aborted from outside its scope
}

You can use this inside some other loop, allowing you to define behavior based on whether an exception was thrown. 您可以在其他循环中使用此方法,从而允许您根据是否引发异常来定义行为。 This code is in C#; 这段代码在C#中; it is syntactically very close to Java but I'm a little light on Java's libraries so substitute proper class names/method calls as necessary: 它在语法上与Java非常接近,但是我对Java的库了解不多,因此可以根据需要替换适当的类名/方法调用:

int day = 0;
while(true) //we will manually break out of the loop once the user enters a valid value
   {
      try
      {
        //Ask user for input
        string input = Console.ReadLine();
        day = Int32.Parse(input); //this will throw an exception if input is not numeric

        //You can throw your own exception within a try block too
        if (day < 1 || day > 31) throw new Exception("Date not within proper bounds");

        break; //if the parse worked and the value passed the validation, end the loop.
      }
      catch(Exception ex) //You can catch something more specific
      {
        //The parse failed; tell the user that they screwed up, and how
        Console.WriteLine("Invalid entry: " + ex.Message);
        //skip the rest of the loop's code and start a new iteration of the loop
        continue; 
      }
   }

The behavior of this construct is that while the user keeps entering values that cannot be turned into a number between 1 and 31, exceptions will be thrown, caught, and used to perpetuate the loop. 这种构造的行为是,当用户不断输入不能转换为1到31之间的数字时,异常将被抛出,捕获并用于使循环永久化。 As soon as the user enters something you can work with, execution flow will move past this loop to whatever is next. 一旦用户输入了您可以使用的内容,执行流程就会越过此循环,移至下一个循环。

暂无
暂无

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

相关问题 在Java中,如何确定输入值是否为整数,然后又存储该值而不必再次询问? - In Java, how do I determine if an input value is an integer and then also store the value without having to ask again? 如何检查 integer 字符串 - How to check for integer string Java:如何询问用户是否想再玩一次 - Java: How to ask the user if he/she wants to play again 如何在 JAVA 中检查输入是整数还是字符串等? - How can I check if an input is a integer or String, etc.. in JAVA? 如何检查扫描器是否为特定字符串 + 任何正整数 [Java] - How to check if a Scanner is a specific String + any positive integer [Java] 如何检查文件是否存在,如果不存在,请循环循环以再次请求新文件名? - How to check if a file exists and loop to ask for new filename again if it doesn't exist? 我将如何在 java 中创建一个循环,要求用户从数组列表中选择一个 class 并且如果他们输入无效值再次询问? - How would I make a loop in java that will ask the user to pick a class from the array list and if they enter an invalid value to ask again? 如何循环问数字是否为整数? - How to loop ask if a number is an integer? 如何在Java中将String转换为Integer - how to convert String into Integer in java 如何问用户是否要重新输入程序(如果键入了字符/字符串而不是数字)? - How to ask user if he wants to start program all over again if he typed a char/string instead of a number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM