我正在为类开发一个程序。
我需要使用扫描器类读取用户的输入。
然后我需要将这些数据传递给带有 while 循环的数组列表。
在我的 while 循环中,我需要一个条件语句来检查输入的是 0 还是负数。
如果用户输入负数或 0,则循环结束,代码进入下一个过程...
我目前面临的问题是:
-我所有的输入值都没有被处理
-我必须输入值0 3次才能退出循环
-0 被传递到我不想要的数组列表
到目前为止,这是我的代码:
import java.util.*;
public class questionAvg3
{
public static void main(String[]args)
{
Scanner input_into = new Scanner(System.in);
ArrayList<Integer> collector = new ArrayList<Integer>();
System.out.println("Enter 0 or a negative number to end input");
System.out.println("Enter a positive integer to populate the arraylist");
while ((input_into.nextInt() !=0) || (input_into.nextInt() < 0)){
System.out.println("Type another int or exit");
collector.add(input_into.nextInt());
}
int minValue = collector.get(0);
int maxValue = collector.get(0);
//int avgValue = collector.get(0);
//int total = 0;
for(Integer i: collector){
if( i < minValue) minValue = i;
if( i > maxValue) maxValue = i;
}
System.out.println("The max value int is: " + maxValue);
System.out.println("The min value int is: " + minValue);
}
}
最佳答案
while ((input_into.nextInt() !=0) || (input_into.nextInt() < 0)){
System.out.println("Type another int or exit");
collector.add(input_into.nextInt());
}
这确实需要 3 个整数才能传递。因为 nextInt
总是寻找下一个输入值。
你需要的是
int input = input_into.nextInt();
while ((input !=0) || (input < 0)){
System.out.println("Type another int or exit");
collector.add(input);
input = input_into.nextInt();
}
关于java - 创建条件语句以对应扫描仪输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33266124/