java - 创建条件语句以对应扫描仪输入

标签 java arrays conditional

我正在为类开发一个程序。

我需要使用扫描器类读取用户的输入。 然后我需要将这些数据传递给带有 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/

相关文章:

Java 代码,安全

java - Spring JPA : Insert succesfully but Update Failed (javax. persistence.PersistenceException:托管刷新期间出错)

C动态分配结构数组及其组件

javascript - 将 excel 二维数组转换为包含列名的嵌套属性对象

ruby-on-rails - Rails 回调 : Use if more than once as conditional in a callback

sql - SQL:一个值的总和,但仅用于不同的ID-条件总和?

exception - 如果您是唯一接触代码的人,是否需要try/except block ?

java - 查找整数中数字的值(以十六进制定义)

java - RSS 提要描述返回 '<'

python - 在Python中迭代numpy数组的更快方法是什么