[英]How to put input into 2 different arrays
I am quite new to Java and am trying to figure out how I would be able to get each alternate input to be stored into different arrays.我对 Java 很陌生,正在尝试弄清楚如何将每个备用输入存储到不同的数组中。 Within my code, I have an infinite loop which gets the program to keep on asking for an input.在我的代码中,我有一个无限循环,它让程序继续请求输入。 I want the inputs to be stored into 2 different arrays.我希望将输入存储到 2 个不同的数组中。 For example, if I was to input 1, 7, 45, 23, 36 I would want 1, 45, and 36 to be stored within the 'valueOne' array and 7 and 23 to be stored within the 'valueTwo' array.例如,如果我要输入 1、7、45、23、36,我希望将 1、45 和 36 存储在“valueOne”数组中,将 7 和 23 存储在“valueTwo”数组中。 Thanks in advance提前致谢
import java.util.Scanner;
public class arraysTest {
public static void main(String[] args) {
double[] valueOne = new double[50];
double[] valueTwo = new double[50];
Scanner s = new Scanner(System.in);
while(true) {
System.out.println("Input a value");
int userInput = s.nextInt();
}
}
}
This should work这应该工作
import java.util.Scanner;
import java.util.ArrayList;
public class arraysTest {
public static void main(String[] args) {
ArrayList<double> v1 = new ArrayList<double>();
ArrayList<double> v2 = new ArrayList<double>();
Scanner s = new Scanner(System.in);
int i=0;
while(true) {
i++
System.out.println("Input a value");
int userInput = s.nextInt();
if(i%2==1) v1.add(userInput);
else v2.add(userInput);
}
}
}
You can try this:你可以试试这个:
I'm not checking array limits我不是在检查数组限制
public static void main(String[] args) { double[] valueOne = new double[50]; double[] valueTwo = new double[50]; Scanner s = new Scanner(System.in); int currentArray = 1; int currentIndexArrOne = 0; int currentIndexArrTwo = 0; while (true) { System.out.println("Input a value"); int userInput = s.nextInt(); if (currentArray == 1) { valueOne[currentIndexArrOne] = userInput; currentIndexArrOne++; currentArray = 2; } else { valueTwo[currentIndexArrTwo] = userInput; currentIndexArrTwo++; currentArray = 1; } } }
Basically you can have a flag like isEven
etc. Then you can check if the input value is in the odd/even.基本上你可以有一个像isEven
等的标志。然后你可以检查输入值是否在奇数/偶数中。
And for the Scanner, you have to use the same types with your arrays.对于 Scanner,您必须对数组使用相同的类型。 Other than you can get type errors除了你可以得到类型错误
boolean isEven = false;
int oneIterator=0; //iterate over the arrays.
int twoIterator=0;
while(true) {
System.out.println("Input a value");
double userInput = s.nextDouble();
if (isEven){
valueOne[oneIterator]=userInput;
oneIterator++;
}
else {
valueTwo[twoIterator]=userInput;
twoIterator++;
}
isEven = !isEven; // for your case no matter the value of isEven is,
// just turn opposite
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.