我有一个代码段(请参见下面的代码段),该代码段生成如下所示的数组:[0,3,1,-2,0,-1,1,1,-2]。此处的整数表示从一个位置到另一位置的运动。我想将数值转换成表示从0开始的方向的文本。正数表示向东的步数-因此数字3将转换为“ eee”,数字2将转换为“ eee” “ ee”等。负值表示在相对的直接西边的步长,因此-2将显示为ww
,依此类推。任何运动都不能表示为0。
对于这一切我还是很陌生,不确定如何从数组中获取值并将它们转换为上述指令。
下面的代码显示了整数数组的生成方式-从前一个整数减去下一个整数以获得整数之间的步数。
int [] differenceX = new int [noOfRecordsX];
differenceX [0] = 0;
for( int i=0; i < noOfRecordsX -1 ;i++)
{
differenceX [i+1]= inputX [i+1] - inputX[i];
}
从这里,我想生成描述各个方向上的步骤的文本,以便该数组:
[0,3,1,-2,0,-1,1,1,-2]
将被转换为以下字符串:
0,eee,e,ww,0,w,e,e,ww
答案 0 :(得分:1)
您可以使用以下代码进行操作:
int arr[] = { 0, 3, 1, -2, 0, -1, 1, 1, -2 };
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 0) { // west
for (int j = arr[i]; j < 0; j++) {
System.out.println("w");
}
} else if (arr[i] > 0) { // east
for (int j = 0; j < arr[i]; j++) {
System.out.println("e");
}
}
}
答案 1 :(得分:1)
如果您希望取回该字符串而不是仅写入控制台,请尝试以下操作:
private void testMyMethod(){
String resultString = "";
int[] array = { 0, 3, 1, -2, 0, -1, 1, 1, -2 };
for(int step : array){
String direction = convertToDirection(step);
// Adding a comma -- as you requested
// just add this in case you what to indicate a start point ==> X
if(direction.isEmpty()){
resultString = resultString.concat("X");
}
else{
resultString = resultString.concat(direction);
}
resultString = resultString.concat(",");
}
resultString = resultString.subString(0, resultString.length()-1);
myTextView.setText(resultString);
}
private String convertToDirection(int step){
String direction = "";
if(step > 0){
direction = "e";
}
else if(step < 0){
direction = "w";
}
String result = "";
int len = Math.abs(step);
for(int i = 0; i < len; i++){
result = result.concat(direction);
}
return result;
}
编辑:
不太冗长的解决方案:
private void testMyMethod(){
int[] array = { 0, 3, 1, -2, 0, -1, 1, 1, -2 };
StringBuilder sb = new StringBuilder();
for(int step : array){
sb.append(convertToDirection(step).concat(","));
}
// Remove the last ","
sb.deleteCharAt(sb.length()-1);
myTextView.setText(sb.toString());
}
private String convertToDirection(int step){
if(step == 0) return "0";
String direction = step > 0 ? "w" : "e";
int len = Math.abs(step);
return new String(new char[len]).replace("\0", direction);
}
借用此解决方案中的new String(new char[len]).replace("\0", direction);
:
Repeat String
答案 2 :(得分:0)
我们最好使用char重复而不是循环。以不同的方式查看Simple way to repeat a String in java。
int arr[] = { 0, 3, 1, -2, 0, -1, 1, 1, -2 };
StringBuilder output = new StringBuilder();
for(int step : array){
int length = Math.abs(step);
if (step < 0) { // west
output.append(new String(new char[length]).replace("\0", "w"));
}
else if (step > 0) { // east
output.append(new String(new char[length]).replace("\0", "e"));
}
else output.append("0");
}
}