【发布时间】:2019-01-26 11:37:19
【问题描述】:
所以这是一个与问题有关的问题。在 codechef (https://www.codechef.com/problems/FRK) 上。我不知道为什么我需要将字符串数组的大小增加 1 并运行循环小于等于(
int nooffriends=0;
Pattern p = Pattern.compile("[^A-Za-z0-9.]");
Scanner scan = new Scanner(System.in);
int noofUsers=scan.nextInt();
if(noofUsers<1||noofUsers>5000)
return;
String array[]=new String[noofUsers+1]; //need to increase this size to get correct answer
for(int i=0;i<=noofUsers;i++){ //had to put '<=' instead '<'(why)
array[i]=scan.nextLine();
// if(array[i].charAt(0)<89||array[i].charAt(0)>122)
// return;
Matcher m = p.matcher(array[i]);
if (m.find())
break;
if(array[i].contains("ch")||array[i].contains("he")||array[i].contains("ef"))
nooffriends++;
}
System.out.print(nooffriends);
} }
【问题讨论】:
-
为什么还需要一个数组?如果只是对当前元素进行操作
-
这是一个很好的解决方案。我不需要那个数组。谢谢。但即使我想知道增加大小的原因..
-
它的大小没有增加。正如我在答案中写的那样 nextInt() 没有读取换行符。这就是为什么在您的循环中,第一个 nextLine() 从上一次调用 nextInt() 中读取新行。只需在循环之前添加一个额外的 nextLine() 就可以了
-
或者总是使用 nextline() 然后解析为 int
标签: java arrays string for-loop logic