简体   繁体   English

检查字符串是否有字符循环

[英]Check string for a character loop

I need to validate user input string to make sure it contains a comma.我需要验证用户输入字符串以确保它包含逗号。 If it does not contain a comma it must print "Error" and allow for the user to re-enter input.如果它不包含逗号,则必须打印“错误”并允许用户重新输入。 I'm just not sure which loop to use.我只是不确定要使用哪个循环。 If else may work, but I need it to loop back to the scanner for the user input.如果其他可能有效,但我需要它循环回扫描仪以获取用户输入。 Or a while loop that uses .contains?还是使用 .contains 的 while 循环? Thanks.谢谢。

If you want to use a loop, I recommend the for-each loop:如果你想使用循环,我推荐 for-each 循环:

boolean found = false;
while (found == false) {
    String input = "this is a sentence, with a comma"; // read input here
    for (char ch: input.toCharArray()) {
        if (ch == ',')  {
            found = true;
        } 
    }
    if (found == false) {
        System.out.println("Error");
    }
}

there will probably be functions built-in in Java for this, like "string.contains(character)" returning a boolean value Java 中可能会为此内置函数,例如“string.contains(character)”返回一个布尔值

input.contains(",")

for loop will be best for such situation. for 循环最适合这种情况。 But you can solve this problem using any of your preferred loops.但是您可以使用任何您喜欢的循环来解决这个问题。

Solution using for loop使用for循环的解决方案

lets say the string you get is in a variable string1假设您得到的字符串在变量 string1 中

enterdata: //ask for user to enter the string here
        for(int i=0;i<string1.length();i++){
            char c = string1.charAt(i);
            if(",".equals(c))
                continue correct;

            }
                if(true) continue enterdata; //this is just like goto statement
        correct:

        //write your code here

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

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