我只是在这一点上学习基本的东西,但是我已经试图将用户输入带入下面的ArrayList并验证该输入不是负数。我可能在思考..但如果你能提供帮助,请告诉我。
由于
public static ArrayList<Double> readcuinput()
{
ArrayList<Double> cuinput;
cuinput = new ArrayList<Double>();
boolean IsNegative;
do{
IsNegative = false;
System.out.println("Enter value, "
+ "Q to quit: ");
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
cuinput.add(in.nextDouble());
for (int i = 0; i < cuinput.size();i++)
{
if (cuinput.get(i) < 0)
{
System.err.println("Error: Must not be a Negative Value");
IsNegative = true;
}
}
}
}while(IsNegative = true);
return cuinput;
答案 0 :(得分:0)
首先在=
条件中将==
更改为while
。
其次,如果最后一个输入是否定,请将其从数组中删除:
...
if (cuinput.get(i) < 0) {
System.err.println("Error: Must not be a Negative Value");
IsNegative = true;
cuinput.remove(i); // ADD THIS
}
...
答案 1 :(得分:0)
简化
public static ArrayList<Double> readcuinput() {
ArrayList<Double> cuinput= new ArrayList<Double>();
Scanner in = new Scanner(System.in);
while (in.hasNextDouble()) {
double value = in.nextDouble();
if (value < 0) {
System.err.println("Error: Must not be a Negative Value");
break;
}
cuinput.add(value);
}
return cuinput;
}