【发布时间】:2017-06-28 00:01:26
【问题描述】:
我只需要找到一种方法来验证输入,这样如果第一个数组输入(主队)丢失,它会显示消息“没有主队进入”。
示例输入 =“埃弗顿 : 利物浦 : 1 : 1” 缺少主队示例“:利物浦:1:1”
如你所见,我的尝试如下,我想不出如何解决这个问题:
if (stats.get(i)[0] == null){
System.out.println("no home team name entered");
}
这是我的完整代码:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<String[]> stats = new ArrayList<>(); //initialize a container to hold all the stats
System.out.println("please enter match results:");
while(sc.hasNextLine())
{
String input = sc.nextLine();
String[] results = input.split(" : ");
if(results.length == 4)
{
stats.add(results);
}
else if(input.equals("stop"))
break;
else
System.out.println("Error reading input");
}//end of while
for(int i = 0; i < stats.size(); i++)
{
if (stats.get(i)[0] == null){
System.out.println("no home team name entered");
}
try{
System.out.println(stats.get(i)[0] + " " + Integer.valueOf(stats.get(i)[2]) + " : " +
Integer.valueOf(stats.get(i)[3]) + " " + stats.get(i)[1]);
}catch (Exception e) {
//do nothing with any invalid input
}
}
}
【问题讨论】:
-
所以。您的尝试做了哪些不应该做的事情?它不应该做什么?
-
它应该告诉用户他们没有在[0]中输入值,但它只是什么也没说,它跳过了if语句
-
if (stats.get(i)[0] == null || stats.get(i)[0].trim().isEmpty()){? - 添加System.out语句来测试值或使用调试器进行简单的运行可能会有所帮助
标签: java arrays loops arraylist