[英]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.