我的数组在字符串的开头填充。然后用户可以输入新的字符串。我希望我的数组向右移动,例如{a,x,x,x}
应将a移动到右{x,a,x,x}
,以便新条目可以向上移动。当我运行我的代码时,它将输入的字符串放在数组的第一个位置,但是在下一步中它不会移动输入的字符串,而是打印出一个仅填充了预定义字符串的数组。为什么它不包含我输入的字符串?
public static void main(String args[]) {
int i;
String n = new String("n");
Scanner sc = new Scanner(System.in);
String a;
String affe [] = new String [5];
Arrays.fill(affe, n);
a = sc.next();
affe[0] = a;
System.out.println(Arrays.toString(affe));
for(i = 0; i<affe.length-1; i++){
affe[i] = affe[i+1];
}
System.out.println(Arrays.toString(affe));
}
答案 0 :(得分:1)
你正在以错误的方式复制。
更改此行:
affe[i] = affe[i+1];
到
affe[i+1] = affe[i];
但是你还需要改变循环的顺序从后到前。否则,每次后续迭代都会带来从开始向前到结束的一个值。所以将循环更改为:
for (int i = affe.length - 2; i >= 0; i--) {
affe[i+1] = affe[i];
}
答案 1 :(得分:1)
尝试
Collections.rotate(Arrays.asList(affe), 1);
答案 2 :(得分:0)
如果我理解你的问题,你只需使用ArrayList
:
import java.util.ArrayList;
import java.util.Scanner;
class MovingItems
{
public static void main(String args[])
{
//create empty ArrayList
ArrayList<String> affe = new ArrayList<String>();
//fill it with data
String n = new String("n");
for(int i=0; i<5; i++){affe.add(n);}
// confirm and Check
System.out.println("Original Array: " + affe);
// get the user input three times (just for example)
Scanner sc = new Scanner(System.in);
String a = sc.next();
// add it always to index 0
// the ArrayList automatically pushes other values
affe.add(0,a);
// remove last item if you want to keep the same size (original size)
affe.remove(affe.size()-1);
// check and confirm
System.out.println("Array After Getting First Value: " + affe);
// again with the second value (for testing)
a = sc.next();
affe.add(0,a);
affe.remove(affe.size()-1);
// check and confirm
System.out.println("Array After Getting Second Value: " + affe);
// the same with third value
a = sc.next();
affe.add(0,a);
affe.remove(affe.size()-1);
// check and confirm
System.out.println("Array After Getting Third Value: " + affe);
// close resources
sc.close();
}
}
<强>输出:强>
Original Array: [n, n, n, n, n]
a
Array After Getting First Value: [a, n, n, n, n]
b
Array After Getting Second Value: [b, a, n, n, n]
c
Array After Getting Third Value: [c, b, a, n, n]