我对java比较陌生,没有指针的引用传递让我感到困惑。我为家庭作业编写了一个函数,要求我返回用户输入的长度,并将使用输入分配给传入的数组,当方法退出用户输入数组丢失时,会出现什么问题。
public static int readArray(char[] intoArray)
{
char[] capture = captureInputAsCharArray(); //User input comes back as char[]
System.arraycopy(intoArray,0, capture, 0, capture.length);
return capture.length;
}
public static main(String[] args)
{
size = readArray(arrItem7); // item 7
System.out.println(size);
printOneInLine(arrItem7); // prints individual elements of array
}
答案 0 :(得分:8)
因为System.arraycopy()
向后有参数。
http://download.oracle.com/javase/6/docs/api/java/lang/System.html
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
交换intoArray
和capture
:
System.arraycopy(capture,0, intoArray, 0, capture.length);
答案 1 :(得分:0)
要做你想做的事(获取用户输入并返回其大小),你可以这样做:
import java.util.*;
class Main{
public static void main(String argv[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter something");
String line = sc.nextLine();
char [] my_array = line.toCharArray();
System.out.println("You entered an input of length "+line.length());
}
}
它会给出这个:
$ java Main
Enter something
Hello
You entered an input of length 5
答案 2 :(得分:-2)
引用本身按值传递。在这种情况下,您应该返回非常数组(capture
)本身而不是长度。