编写使用在一个数字,表示一个字符串数组的大小(n)的第一读取扫描器对象的程序。创建字符串数组使用第一号码作为大小。然后,将读取(n)的城市都在同一行,并将它们存储在数组中。最后,你会读到一个字符(同线城市)。然后,程序便会进入城市的阵列和打印屏幕的次数char是在城市。请确保您处理的情况下(A!= A)。
import java.util.Arrays;
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
String myarray[] = new String[length];
char ch;
for (int i = 0; i < myarray.length; i++) {
myarray[i]=scanner.next();
}
ch= scanner.next().charAt(0);
char ch1= Character.toUpperCase(ch);
char ch2= Character.toLowerCase(ch);
for(int y=0; y<myarray.length; y++){
int counter=0;
for(int z=0; z<myarray.length; z++){
if(myarray[y].charAt(z)==ch1){
counter++;
}else if(myarray[y].charAt(z)==ch2){
counter++;
}
}
System.out.print(counter+" ");
}
}
}
例如输入:
4
多伦多哈利法克斯特鲁罗渥太华ŧ
示例输出:
2 0 1 2
我的输出:
1 0 1 2
要计算所需的字符量忽略的情况下,你可以从字符串和所需的字符使用Character.toLowerCase()
字符。这是同样的,当你做str.toLowerCase()
,但没有新的字符串创建。
对于这个计数任务,你并不需要修改字符串(如str.replaceAll()
)。一般来说,你的做法是好的,但你必须在你的for
循环的一些错误。
public class Problem {
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
int[] count = count(readCities(scan), readChar(scan));
System.out.println(Arrays.stream(count)
.mapToObj(Integer::toString)
.collect(Collectors.joining(" ")));
}
}
private static String[] readCities(Scanner scan) {
String[] cities = new String[scan.nextInt()];
for (int i = 0; i < cities.length; i++)
cities[i] = scan.next();
return cities;
}
private static char readChar(Scanner scan) {
return scan.next().charAt(0);
}
private static int[] count(String[] cities, char ch) {
int[] count = new int[cities.length];
for (int i = 0; i < cities.length; i++)
for (int j = 0; j < cities[i].length(); j++)
if (Character.toLowerCase(cities[i].charAt(j)) == Character.toLowerCase(ch))
count[i]++;
return count;
}
}
for(int z=0; z<myarray.length; z++){
更改上面的for循环提及如下
for(int z=0; z<myarray[y].length(); z++){
myarray.length
将代表输入串的总数(4)即,环路将迭代,直到第四字符或字符串,所以第一字符串是“多伦多”和循环将迭代“O” remainings不会迭代的第二直到occurence。
qazxsw POI将代表字符串中的字符的总数目。所以,现在的循环将遍历字符串的所有字符。
首先,它往往是最好的使用评论//和/ *文本* /
其次,你的计数器是不工作,因为你只算到数组的长度,而不是字符串,而是使用“String.replaceAll(字符串,字符串);”和“string.length减()”,你可以指望它。
这会给你的字符计数错误。
输入:2 A B吨
使用变量
•长度(INT)
•阵列(字符串[])
•CH(炭)
myarray[y].length()
该代码计算在这样的字符串中的字符。担心大写和小写?在你的输入使用String.toLowerCase()和.toUpperCase()。
[字符串长度] - [更换炭后字符串长度]
它有时是非常有用看评论。看看戴夫,你会发现这个错误。