创建一个条件语句以对应扫描仪输入。

3

我正在开发一个课程项目程序。

我需要使用scanner类读取用户的输入。然后我需要通过while循环将这些数据传递给一个ArrayList。 在我的while循环中,我需要一个条件语句来检查是否输入了0或负数。
如果用户输入负数或0,则循环结束,代码进入下一个流程...

我目前面临的问题是:

- 我所有的输入值都没有被处理

- 我必须输入0三次才能退出循环

- 0被传递到我的ArrayList中,而我不想要它

这是我目前的代码:

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);

}
}
3个回答

5
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();
        }

这会创建一个无限循环。你应该在 while 循环的结尾更新你的 input - gonzo
我已经实现了这个功能,但现在卡在了一个无限循环中,一直打印“输入另一个整数或退出”。 - Anthony J
1
@AnthonyJ 在你的 while 循环的末尾添加 input = input_into.nextInt(); 即可。 - gonzo
@sᴜʀᴇsʜᴀᴛᴛᴀ 真遗憾我没有因此获得声望。 :p - gonzo

1

Your problem is right here:

while ((input_into.nextInt() !=0) || (input_into.nextInt() < 0)){
System.out.println("Type another int or exit");
    collector.add(input_into.nextInt());
}

你需要输入三次0是因为你调用了input_into.nextInt()三次!这意味着你的程序正在等待一个整数,根据你的比较进行评估,然后再次执行相同的操作,最后一次是为了collector.add()
我认为你需要更好地理解如何使用比较运算符。
例如,当你说(input_into.nextInt() != 0) || (input_into.nextInt() < 0)时,你实际上是在说这个数字小于零或大于零。 由于你的哨兵值是任何小于等于零的数字,你只想在输入大于零时继续。这给你以下结果:
    int input = input_into.nextint();
    while (input > 0){
       System.out.println("Type another int or exit");
       collector.add(input);
       input = input_into.nextint();
    }

1
非常完美,谢谢你帮助我更好地理解并解决了我的问题。 - Anthony J
@AnthonyJ 我建议你将循环改为我上面的方式,这样更容易阅读,而且性能更好,因为每次迭代比你最初的循环设置少进行一次比较。 - Evan Bechtol

0
在循环内使用一个变量,并将其用于测试循环继续条件。
  int variable=input.nextInt(); //get initial input

  while (variable<=0)
    {
        //get next input
        variable=input.nextInt();
    }//end while

这将循环直到输入小于等于0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接