I am trying to read an input like this:
5 3 3
1 2 3 4 5
5 4 3 2 1
When I use the scanner and try something like this:
Scanner sc = new Scanner(System.in);
int n, x, y;
String[] temp = sc.nextLine().split(" ");
n = Integer.parseInt(temp[0]);
x = Integer.parseInt(temp[1]);
y = Integer.parseInt(temp[2]);
int[] a, b;
a = b = new int[n];
String[] t = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(t[i]);
}
String[] f = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
b[i] = Integer.parseInt(f[i]);
}
This just prints that the arrays 'a' and 'b' are same;
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
12
How can I read this input?
The problem with your code is not how you read the input, but this line here:
a = b = new int[n];
In this line, you set a
and b
to the same new int
array. You did create a new array here, but you only created one. Both a
and b
refer to that same one. So when you are doing b[i] =...
, you are in fact overwriting the values you've just written to it in the first loop.
You should create two arrays:
a = new int[n];
b = new int[n];
Note that another way to read the input is to use nextInt
, but your way is okay too.
Scanner sc = new Scanner(System.in);
int n, x, y;
n = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
int[] a, b;
a = new int[n];
b = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
for(int i = 0; i < n; i++){
b[i] = sc.nextInt();
}
This is causing the problem.
a = b = new int[n];
Both a, b are referencing the same array object. Hence, the later input is overriding the previous input. Change this to:
a = new int[n];
b = new int[n];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.