简体   繁体   English

Java字符串验证循环

[英]Java String Validation Loop

I have a quick question regarding Java. 我对Java有一个快速的问题。 I'm currently studying for a coding assignment coming up regarding arrays. 我目前正在研究有关数组的编码任务。 Essentially the assignment is making a few String arrays and randomly generating numbers to pick elements of the array. 本质上,分配是制作一些String数组,并随机生成数字以选择该数组的元素。

One of the requirements of the assignment is to do validation, the String that is a result of picking from the two arrays. 分配的要求之一是执行验证,这是从两个数组中选取的结果。 Our rules for validation is that the string can't be greater than 8 characters in length. 我们的验证规则是字符串的长度不能超过8个字符。 If it's greater than 8 we need to randomly generate another string that is less than or equal to 8 characters. 如果大于8,则需要随机生成另一个小于或等于8个字符的字符串。

I've tried using a do-while and a while(loopFlag) validation loop. 我尝试过使用do-while和while(loopFlag)验证循环。 But I just can't seem to get it to work properly. 但是我似乎无法使其正常工作。 Typically what will happen is the console runs into an error and just gets stuck in the validation loop. 通常情况下,控制台将出错并陷入验证循环中。 I tried making an int characterLength and using the .length() method but it doesn't seem to work. 我尝试制作一个int characterLength并使用.length()方法,但它似乎不起作用。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Thanks! 谢谢!

Random random = new Random();
String [] results = new String[50];
int index = 0;

while(index < results.length) {

    //to get some random values
    //String num = String.valueOf(someByteArray);
    String num = String.valueOf(random.nextInt()); //value from first array
    num += String.valueOf(random.nextInt()); //value from second array


    // to long?
    if(num.length() > 8) {
        System.out.println("Not valid " + num);
        continue;
    }

    try {
        //is it number?
        Integer.valueOf(num);
    } catch (NumberFormatException e) {
        //it was not number or to big for int
        System.out.println("Not valid " + num);
        continue;
    }

    results[index++] = num;
    System.out.println("Valid " + num);
}

It all ended up being the location of where i ended my do-while. 最终所有这些都是我结束工作的地方。 My prof taught us that you should always validate your inputs before they are added to your arrays/variables. 我的教授告诉我们,在将输入添加到数组/变量之前,应始终对其进行验证。

I ended up using the do-while loop but included all of the code from the for loop instead of ending the do-while before I add the result to the array. 我最终使用了do-while循环,但是包含了for循环中的所有代码,而不是在将结果添加到数组之前结束了do-while。

do { ...... }while(vanityPlate.length()<9); 做{......} while(vanityPlate.length()<9);

Thanks for all the help guys! 感谢所有的帮助!

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

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