我真的是Java新手,代码有些问题。未检测到错误,但输出为奇数。 目标是将数组中的数据向左移动。例如: x = {1,2,3} 新数组应为{2,3,1}。
现在下面的代码仅给我{0,0,0}。如果您指出错误并告诉我该怎么办会很好。事先非常感谢!
CC = g++
#.PHONY: sfml-app
LIBS = -lsfml-graphics -lsfml-window -lsfml-system
APPLICATION = sfml-app
INCLUDE_DIR = -I include/
SOURCE_DIR = source
OUTPUT_DIR = bin
SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp)
OBJECTS = $(notdir $(patsubst %.cpp, %.o, $(SOURCES)))
#$(OUTPUT_DIR)/$(APPLICATION): $(OBJECTS)
#bin/sfml-app: $(OBJECTS)
#sfml-app: $(OBJECTS)
#$(APPLICATION): $(OBJECTS)
$(CC) $(OUTPUT_DIR)/*.o $(LIBS) -o $(OUTPUT_DIR)/$(APPLICATION)
%.o: $(SOURCE_DIR)/%.cpp
$(CC) -c $< $(INCLUDE_DIR) -o $(OUTPUT_DIR)/$@
clean:
rm $(OUTPUT_DIR)/*
print-% : ; @echo $* = $($*)
答案 0 :(得分:2)
作为实现目标的简单解决方案,您可以使用此
public static int[] shiftone(int[] n, boolean left) {
// you don't need to shift anything if length = 1
if (n.length < 2) {
return n;
}
if (left) {
// save first element
int save = n[0];
for (int i = 1; i < n.length; i++) {
// shift from 1 to n
n[i-1] = n[i];
}
// insert saved element to array
n[n.length - 1] = save;
} else {
// the same
int save = n[n.length - 1];
for (int i = 1; i < n.length; i++)
n[n.length - i] = n[(n.length - 1) - i];
n[0] = save;
}
return n;
}
答案 1 :(得分:1)
有一种非常快速的方法将数组元素从一个位置复制到另一个位置。我不知道这是否对您有帮助,因为在我看来您的问题是家庭作业。不过,我会在代码中加上适当的注释...
public class Answer {
public static void main(String[] args) {
//test case
int[] input = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(input));
//save the first element in the temporary variable
int temp = input[0];
//the fastest way to copy the array elements
//1st parameter is the source array
//2nd parameter is the source position (read: from which element to copy)
//3rd parameter is the destination (in this case the same array)
//4th parameter is the destination position (read: where to store the 1st element)
//5th parameter is the length of elements to copy (read: how many)
System.arraycopy(input, 1, input, 0, input.length - 1);
//finally store the saved element to the end
input[input.length - 1] = temp;
System.out.println(Arrays.toString(input));
}
}
答案 2 :(得分:1)
如果我们不想自己编写移动代码,可以使用方法Collections.rotate
。它花费List
并将元素旋转给定距离。要使用它,我们需要将int
数组转换为List<Integer>
。旋转后的列表将转换回int
数组。
protected static int[] move(int[] input, int distance) {
List<Integer> inputList = Arrays.stream(input).boxed().collect(Collectors.toCollection(ArrayList::new));
Collections.rotate(inputList, distance);
return inputList.stream().mapToInt(Integer::intValue).toArray();
}
用法:
public static void main(String[] args) throws Exception {
int[] input = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
int moveLeftOnce = -1;
int[] moved = move(input, moveLeftOnce); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
}
请注意:
由于Collections.rotate
将移动给定列表中的元素,因此该列表必须是可修改的。 ArrayList
就是这种情况。由于存在(JavaDoc),因此代码使用Collectors.toCollection(ArrayList::new)
不能保证返回的
List
的类型,可变性...
通过Collectors.toList
。