[英]User input to 2 separate arrays in Java
I'm completely new to the Java language.我对 Java 语言完全陌生。 I'm still learning and practicing it but while solving a problem, I got stuck at this.
我仍在学习和练习它,但在解决问题时,我陷入了困境。 What I want to do is to add 2 elements per line into 2 separate arrays.
我想要做的是将每行 2 个元素添加到 2 个单独的数组中。 The first element goes to the X array and the second element goes to the Y array.
第一个元素进入 X 数组,第二个元素进入 Y 数组。
public static void main (String[] args) throws IOException {
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
double[] X = new double[n];
double[] Y = new double[n];
String[] elem = reader.readLine().split(" ");
for(int i = 0; i < n; i++)
{
X[i] = Integer.parseInt(elem[n]);
Y[i] = Integer.parseInt(elem[n]);
}
System.out.println(X, Y);
}
input:输入:
3 4 3 4
1 1 1 1
2 3 2 3
where the first column is array X and the second column is array Y. I played with code several times but it still gives me "Index 2 out of bounds for length 2".其中第一列是数组 X,第二列是数组 Y。我玩过几次代码,但它仍然给我“索引 2 超出长度 2 的界限”。
You have to read your lines inside the for loop.你必须阅读里面的线环。
X[i]
corresponds to elem[0]
; X[i]
对应于elem[0]
; Y[i]
corresponds to elem[1]
. Y[i]
对应于elem[1]
。 For example:例如:
import java.io.*;
import java.util.*;
public class App {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
double[] X = new double[n];
double[] Y = new double[n];
for (int i = 0; i < n; i++) {
String[] elem = reader.readLine().split(" ");
X[i] = Integer.parseInt(elem[0]);
Y[i] = Integer.parseInt(elem[1]);
}
System.out.println(Arrays.toString(X));
System.out.println(Arrays.toString(Y));
}
}
This part is not right:这部分不对:
for(int i = 0; i < n; i++)
{
X[i] = Integer.parseInt(elem[n]);
Y[i] = Integer.parseInt(elem[n]);
It seems like it should be好像应该是
for(int i = 0; (i - 1)< n; i+= 2) // adding two because you are reading two values from elem in every iteration. Changed check to i - 1 to fix case where an odd number of entries will cause an ArrayOutOfBoundsException in elem on i/2 + 1
{
X[i/2] = Integer.parseInt(elem[i]);
Y[i/2] = Integer.parseInt(elem[i] + 1);
(There was a bug in my answer here. It has been fixed) (我在这里的回答中有一个错误。已修复)
Alternatively:或者:
for(int i = 0; i < n; i++)
{
if (i % 2 == 0) X[i/2] = Integer.parseInt(elem[i]);
else Y[i/2] = Integer.parseInt(elem[i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.