如何验证字符串数组中的用户输入?

时间:2016-12-27 16:58:22

标签: java arrays validation for-loop

在我开始之前,我想说;我之前已经问过这个问题,并且被我改变程序的方式所淹没,而不是我的问题的明确答案 - 我很满意我的代码我只想验证它:)

就像标题暗示我试图验证我的字符串数组一样,我是Java新手并且一直试图在for循环中放置几个​​布尔条件但是代码似乎总是忽略循环并继续正常运行,例如我写" if(words == null)print" Error""程序正常运行,就好像条件不存在,即使数组位置为空。

String [] football_list = new String [100];         //Declare the array 
int counter = 0;                                //Initialize counter integer

scanner = new Scanner(System.in);{      //Import Scanner
System.out.println("Input as follows; "); {     //User instructions
System.out.println("Home team : Away team : Home score : Away score");

String line = null; { // Creates a blank string

while (!(line = scanner.nextLine()).equals("")) { // The code in the loop will process only if it is not empty

    if (line.equals("quit")) { // When the user is finished this exits the program
           break;
    } else {
        football_list[counter] = line; // The below String is printed for the amount of values inside the counter integer

        System.out.println("Home team : Away team : Home score : Away score");
    }

    counter++;  // counter is incremented
}

}
for (int i = 0; i < counter; i++) { // A loop to control the Array 
    String[] words = football_list[i].split(":"); // Splits the input into 4 strings
    if(words.equals(null)){

        System.out.println("Null");
        }
    else
    System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output    

    }



}
    }
        }
            }   

我的代码根据用户输入创建了一个运动结果表。用户输入这样的输入&#34; Home_Team:Away_Team:Home_Score:Away_Score&#34;,我想生成一条错误消息,并在其中一个插槽为空时停止该程序。

新错误

for (int i = 0; i < counter; i++) { // A loop to control the Array 
    String[] words = football_list[i].split(":"); // Splits the input into 4 strings
    if (words.length != 4) { // If the length of the array elements does not equal 4 then print error message
        System.out.println("Input was not valid");
        //counter--;
        //i--;
    } else
    {

    System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " [" + words[3].trim() + "]"); // Formats and prints the output    


   }
   }
   }
    System.out.println("                 ");
    System.out.println("                 ");
    System.out.println("                 ");
    System.out.println("        Totals        ");
    System.out.println("-------------------------");
    System.out.println("Total games played: " +  counter);


    }

2 个答案:

答案 0 :(得分:1)

如果您尝试检测

等输入
Tigers:Lions:7

找出words的长度并检查它是否为4。

if (words.length != 4){

    System.out.println("Input was not valid.");
}
else{
    // Print formatted string 
}

另一方面,请确保您了解空数组/字符串和空数组/字符串不相同。空数组{}或空字符串“”有一个值,即使它是空的。

String[] words = football_list[i].split(":"); // Splits the input into 4 strings
if(words.equals(null)){
    System.out.println("Null");
}

此处words永远不会是null,因为您已将其初始化为football_list[i].split(":")。另外,请注意它也永远不会是空数组。

如果在:中找不到football_list[i],则数组将包含一个元素words[0] = football_list[i]

将某些内容初始化为null没有用,因为String line;已经linenull

完整代码应该类似于:

import java.util.Scanner;

public class circle {
    public static void main(String[] args) {
        String[] football_list = new String[100]; // Declare the array
        int counter = 0; // Initialize counter integer

        Scanner scanner = new Scanner(System.in); // Import Scanner
        System.out.println("Input as follows; "); // User instructions
        System.out.println("Home team : Away team : Home score : Away score");

        String line = null; // Creates a blank string

        while (!(line = scanner.nextLine()).equals("")) { // The code in the
                                                        // loop will process
                                                        // only if it is not
                                                        // empty

            if (line.equals("quit")) { // When the user is finished this exits
                                    // the program
                break;
            } else {
                football_list[counter] = line; // The below String is printed
                                            // for the amount of values
                                            // inside the counter integer

                System.out.println("Home team : Away team : Home score : Away score");
            }

            counter++; // counter is incremented
        }

        for (int i = 0; i < counter; i++) { // A loop to control the Array
            String[] words = football_list[i].split(":"); // Splits the input
                                                        // into 4 strings
            if (words.length != 4) {
                System.out.println("Input was not valid.");
            } else
                System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
                    + words[3].trim() + "]"); // Formats and prints the output

        }

    }
}

考虑使用验证器方法,因为有很多验证要做。

它看起来像这样:

public static boolean validateString(String input) {
    if (input.split(":").length != 4) {
        return false;
    }
    for (String info : input.split(":")) {
        if (info.length() == 0) {
            return false;
        }
    }
    return true;
}

你的for-loop逻辑可能是

for (int i = 0; i < counter; i++) { // A loop to control the Array
        String[] words = football_list[i].split(":"); // Splits the input
                                                        // into 4 strings
        if (Main.validateString(football_list[i])) {
            System.out.println(words[0].trim() + " [" + words[2].trim() + "]" + " | " + words[1].trim() + " ["
                    + words[3].trim() + "]"); // Formats and prints the output
        }
        else{
            System.out.println("Your input of " + football_list[i] + " was not valid.");
        }
    }

另外,请考虑使用ArrayList而不是数组。您不必保留counter或将最大输入数设置为100.

答案 1 :(得分:0)

如果您执行此类操作以检查数组是空还是空,该怎么办:

if(words[0] != null && words[0].length() > 0) {
   //it is not null and it is not empty
}else{
   //you can have the error message here
   System.out.println("It's null or empty");
}