简体   繁体   English

检查字符串在数字范围内Java

[英]Check String is in a range of numbers Java

Trying to design a simple lottery program. 试图设计一个简单的彩票程序。 Everything works except checking if the numbers entered are between 1 to 59. 一切正常,除了检查输入的数字是否在1到59之间。

Exercise says the numbers must be stored in a String variable. 练习说数字必须存储在String变量中。

so 所以

if(num<0 || num>59) //wont work for me

Tried making another variable 试图使另一个变量

int numConverted = Integer.parseInt(num)

We haven't covered converting String to int in class though so I don't think this is what expected. 尽管我们没有在类中介绍将String转换为int ,所以我认为这不是所期望的。 Got confused trying that way anyway so probably this is wrong. 无论如何都会感到困惑,所以这可能是错误的。

Here is the code I have currently. 这是我目前拥有的代码。

{
    Scanner scan = new Scanner(System.in);

    String num=""; //num variable is empty untill user inputs numbers

    for(int i =0; i<6; i++) 
    {
        System.out.println("Enter your number between 1-59");
        num = num +" "+ scan.nextLine(); 
    }

    System.out.println("Ticket printed £2. Your numbers are " + num);
}

In your posted code it's obvious that you want the User to supply 6 specific numerical values. 在您发布的代码中,很明显,您希望用户提供6个特定的数值。 These values are appended to the String variable named num (space delimited). 这些值将附加到名为num (以空格分隔)的String变量中。 You need to obviously do a few things here: 您显然需要在这里做一些事情:

1) Make sure the value supplied by the user is indeed a numerical value; 1)确保用户提供的值确实是数字值;

2) Make sure the numerical values supplied fall within the minimum and maximum scope of the lottery itself (which you have stated is: 1 to 59); 2)确保提供的数值落在彩票本身的最小和最大范围内(您所说的范围是1到59);

3) Make sure the number entered by the User hasn't been supplied already. 3)确保尚未提供用户输入的号码。

You've been tasked to store the entered values into a String data type variable and that is all fine but at some point you want to carry out value comparisons to make sure that all the entered values actually play within the limits of the lottery. 您的任务是将输入的值存储到String数据类型变量中,这很好,但是在某些时候您要进行值比较,以确保所有输入的值实际上都在彩票的范围内。

When the User completes his/her entries, you end up with a space delimited string held in the num string variable. 当用户完成他/她的输入时,您最终将在num string变量中保存一个以空格分隔的字符串。 You now need to make sure that these values entered are indeed....numbers from 1 to 59 and none contain alpha characters. 现在,您需要确保输入的这些值的确是....从1到59的数字,并且都不包含字母字符。

In my opinion (and this is only because you need to store entered values into a String variable), it's best to use your String variable to gather User input, then test the input to make sure it is indeed a string representation of an actual integer number. 我认为(这仅仅是因为您需要将输入的值存储到String变量中),最好使用String变量来收集用户输入,然后测试输入以确保它确实是实际整数的字符串表示形式数。 Once this is established then we test to make sure if falls within the value min/max limits (1-59). 一旦确定,我们将进行测试以确保是否在最小/最大限制值(1-59)之内。 Now we need to test to make sure the number entered hasn't already been entered before for this ticket. 现在,我们需要进行测试以确保尚未输入此票证的输入号码。

Of course with each test described above, if one fails then the User should be prompted to re-enter a proper value. 当然,对于上述每个测试,如果测试失败,则应提示用户重新输入适当的值。 You can do this by utilizing a while loop. 您可以利用while循环来做到这一点。 Plenty examples of this in StackOverflow but here's a quick example: 在StackOverflow中有很多示例,但是这里有一个简单的示例:

Scanner scan = new Scanner(System.in);
String ticketNumbers = "";
for(int i = 0; i < 6; i++) {
    Boolean isOK = false;
    while (!isOK) {
        System.out.println("\nPlease enter your desired 6 ticket numbers:\n"
                + "(from 1 to 59 only)");
        String num = scan.nextLine(); 
        //Is the string entered an actual integer number?
        //We use the String.matches() method for this with
        //a regular expression.
        if(!num.matches("\\d+")) {
            System.out.println("You must supply a numerical value! "
                    + "Try Again...");
            continue;
        }
        if (ticketNumbers.contains(num + " ")) {
            System.out.println("The number you supplied has already been chosen!"
                    + " Try Again...");
            continue;
        }
        if (Integer.parseInt(num) >= 1 && Integer.parseInt(num) <= 59) {
            ticketNumbers+= num + " ";
            isOK = true;
        }
        else {
            System.out.println("The number you supply must be from "
                    + "1 to 59! Try Again...");
        }
    }
}
System.out.println("Ticket printed £2. Your numbers are " + ticketNumbers);

How about - 怎么样 -

if(Integer.parseInt(num) < 0 || Integer.parseInt(num) > 59)

This should work, place it after the input. 这应该起作用,将其放置在输入之后。

If it works, please mark this as correct, I need the rep!!! 如果有效,请将其标记为正确,我需要代表!!!

Easy way would be add available numbers (suppose it wont grow more than 60. You can use a loop to add to this as well) 一种简单的方法是添加可用数字(假设它不会增长超过60。您也可以使用循环将其添加到此数字)

String numbers[] = {"1","2","3", "..."};

Then inside the loop 然后进入循环

 Arrays.asList(numbers).contains(num);

You can remove prefixing zero in order avoid conflicts with values like '02' 您可以删除前缀零,以避免与'02''02'值发生冲突

Here everything is String related. 在这里,一切都与String有关。

If you don't want to explicitly convert to int , you could use a regular expression. 如果您不想显式转换为int ,则可以使用正则表达式。

if (num.matches("[1-5]?[0-9]")) {
    ...

This checks whether the String consists of (1) maybe a digit from 1 to 5, followed by (2) definitely a digit from 0 to 9. That'll match any number in the range 0-59. 这将检查String是否包含(1) 可能是1到5的数字,然后是(2) 绝对是0到9的数字。这将匹配0-59范围内的任何数字。

If you've got a whole series of numbers separated by spaces, you could expand this to cover a whole series like this. 如果您有一个由空格分隔的整数序列,则可以将其扩展为覆盖整个整数序列,如下所示。

if (num.matches("([1-5]?[0-9]\\s+)*[1-5]?[0-9]")) {

This matches any number of repetitions (including zero) of "a number followed by spaces", followed by a single repetition without a space. 这匹配“数字后跟空格”的任意重复(包括零),然后是没有空格的单个重复。 The "\\\\s" means "any whitespace character", the "+" after it means "one or more of what precedes", and the "*" means "zero more of what precedes" - which in this case is the term in parentheses. "\\\\s"表示“任何空白字符”,其后的"+"表示“一个或多个前置字符”,而"*"表示“零个前置字符”-在这种情况下,该术语在括号内。

Oh I see what you are trying to do 哦,我明白了您要做什么

This is what you want 这就是你想要的

    Scanner scan = new Scanner(System.in);


String allNums = "";


for(int i =0; i<6; i++) 
{
    System.out.println("Enter your number between 1-59");
    int num = scan.nextInt();//Take the number in as an int 

    if(num >0 && num < 59)//Check if it is in range
    {
        allNums += num + " ";//if it is add it to a string
    }
    else
    {
        System.out.println("Number not in range");
        i--;//go back one iteration if its not in range
    }


}

System.out.println("Ticket printed £2. Your numbers are " + allNums);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM