[英]How to user input a pattern in string at a time and store it as a 2d character array in Java
我陷入一个特殊的问题。 任何帮助都是非常可观的。
假设我得到的行数为8,列数为5。 我如何以以下方式从用户那里获取输入。
Aacvg
Qwn&k
LOpyc
GYhcj
%&fgT
JUIOP
icgfd
Hu*hc
然后计算整个用户定义模式中的'c'数,此处将给出输出= 5。
我尝试将每行输入为String,然后将其转换为2D char数组,但这种方式无法正常工作。 还有如何将每行的字符数限制为列数(此处为5)。
注意:-输入将是整行,然后是下一行。..直到row = 8(对于此示例)。
如果有人能告诉我这样做的方法,我将非常感激(我什至考虑过数组数组)。
我编写了以下代码,但是它无法正常工作,因此如果有人可以编写正确的方法来执行此操作。
Scanner sc = new Scanner (System.in);
for(int i=0;i<row;i++){
String str;
str = sc.nextLine();
for(int j=0;j<column;j++){
char[] charArray = str.toCharArray();
a[i][j]= charArray[j];
if(a[i][j]=='c'){
count= count+1;
}
}
}
建议不要使用数组,而建议使用String
类提供的函数。
这是根据您的示例使用代码实现此目标的一种可能方法。
int row = 8;
int column = 5;
int count = 0;
char searchedCharacter = 'c';
int currentIndex;
boolean searching;
Scanner sc = new Scanner(System.in);
String str;
for (int i = 0; i < row; i++) {
str = sc.nextLine();
currentIndex = -1;
searching = true;
while (searching) {
// indexOf will return -1 if the character was not found in the String
currentIndex = str.indexOf(searchedCharacter, currentIndex + 1);
if (currentIndex > -1 && currentIndex < column) {
count++;
} else {
searching = false;
}
}
}
sc.close();
System.out.println(count);
这样,您将不必处理Array
,也不必处理字符的比较,因为String
对象将为您完成大部分工作。
这也将阻止您在IndexOutOfBoundsExceptions
中运行,因为您不检查charArray[j]
是否实际上是有效的索引,所以它很容易在代码中发生。
也许这是您想要的代码:
import java.util.Scanner;
public class WTF {
public static void main(String[] args) {
new WTF().doIt();
}
private void doIt() {
Scanner sc = new Scanner(System.in);
int row = 8;
int column = 5;
int count = 0;
for (int i = 0; i < row; i++) {
System.out.println("Please enter the row no. " + (i + 1) + ":");
String str = sc.nextLine();
// cut the string to 5 chars
str = str.substring(0, column);
char[] charArray = str.toCharArray();
for (char c : charArray) {
if ('c' == c) {
count++;
}
}
}
System.out.println("The number of c entered is: " + count);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.