我正在研究一个具有以下输入的java程序:
A V V V VV V V V
E F V E VF E V E
C D V C VD B V C
A A V A VA G V A
V D V V VD E V V
A V V A VV V V A
以及以下输出:
R
R
R
R
R
R
如果列中包含最少一个字母R
,则必须打印A-G
,但如果列中只有V
,则必须打印一个空格。我的代码是:
Scanner inputc2 = new Scanner (new File("internalc"));
int sss = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
try{
matrix2[i][j] = inputc2.useDelimiter(" ").next().replaceAll(",", " ");
System.out.println(matrix2[i][j]);
temp2[sss] = matrix2[i][j];//change this
if(temp2[sss].indexOf("N") >= 0){
pc2.println(temp2[sss].replaceAll("N","R"));
}
if(temp2[sss].indexOf(' ') >= 0){
pc2.println(temp2[sss]);
}
sss++;
}
catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
}
在当前程序中,temp2 [sss]与matrix2 [i] [j]完全相同,但它必须是列的字符串。我希望你能帮助我。
亲切的问候, 比约
答案 0 :(得分:1)
您可以替换此行
temp2[sss] = matrix2[i][j];
通过
List<Integer> temp2 = new ArrayList<Integer>();
temp2.add(matrix2[i][j]);
int[] vector = new int[temp2.size()];
for (int i = 0; i < vector.length; i++) {
vector[i] = temp2.get(i);
}
答案 1 :(得分:1)
这是我写的一个示例程序, 输出可能不完全符合您的预期,可以根据您的需要调整正则表达式
public static void main(String[] args) throws Exception {
Pattern pattern = Pattern.compile("[A-G]+[A-G]{0,1}");
Pattern pattern2 = Pattern.compile("[V]+[V]*");
BufferedReader br = new BufferedReader(new FileReader(new File("test.txt")));
String line;
while ((line = br.readLine()) != null) {
StringBuffer sf = new StringBuffer();
//System.out.println(line);
String[] tempArr = line.split(" ");
//System.out.println(tempArr.length);
for(String s : tempArr){
Matcher matcher = pattern.matcher(s);
Matcher matcher2 = pattern2.matcher(s);
if (matcher.find()) {
sf.append("R");
}else if(matcher2.find()) {
sf.append(" ");
}
}
System.out.println(sf);
}
br.close();
}
修改2
你去了
public static void main(String[] args) throws Exception {
Pattern pattern = Pattern.compile("[A-G]+");
Pattern pattern2 = Pattern.compile("[V]+");
List<String[]> mat = new ArrayList<String[]>();
String[] row1 = { "A", "V", "V", "V", "VV", "V", "V", "V" };
String[] row2 = { "E", "F", "V", "E", "VF", "E", "V", "E", };
String[] row3 = { "C", "D", "V", "C", "VD", "B", "V", "C" };
String[] row4 = { "A", "A", "V", "A", "VA", "G", "V", "A" };
String[] row5 = { "V", "D", "V", "V", "VD", "E", "V", "V" };
String[] row6 = { "A", "V", "V", "A", "VV", "V", "V", "A" };
mat.add(row1);
mat.add(row2);
mat.add(row3);
mat.add(row4);
mat.add(row5);
mat.add(row6);
int rowSize = 6;
int colSize = 8;
String[][] matrix = mat.toArray(new String[rowSize][colSize]);
for (int i = 0; i < colSize; i++) {
StringBuffer sf = new StringBuffer();
for (int j = 0; j < rowSize; j++) {
sf.append(matrix[j][i]);
}
Matcher matcher = pattern.matcher(sf.toString());
Matcher matcher2 = pattern2.matcher(sf.toString());
if (matcher.find()) {
System.out.println("R");
} else if (matcher2.matches()) {
System.out.println(" ");
}
}
}
<强>结果:强>
R
R
R
R
R
R