for循环条件和if语句

时间:2014-11-26 17:03:26

标签: java list if-statement for-loop break

我做了一个for循环,当用户输入负值然后给出一条消息时,我希望循环中断。我不希望程序计算负值。

public class test1
{
    public static void main(String[] args)
    {
        PrintStream output = new PrintStream(System.out);
        Scanner input = new Scanner(System.in);
        List<Integer> yolo = new ArrayList<Integer>();
        double sum = 0;
        output.println("Enter your integers\n" + "(Negative=sentinel)");

        // add the values to your empty Array except the negative entries
        for (int entry = input.nextInt(); entry < 0 ; entry = input.nextInt())
        {
            yolo.add(entry);
            if (entry >= 0 )
            {
                sum += entry;
            }
            else {
                output.println("Your list is empty");
            }
        }

我尝试使用Outerloop:并打破外环;但即使在正整数时它也会打破循环。

2 个答案:

答案 0 :(得分:3)

将其更改为

for ( int entry = input.nextInt(); entry >= 0; entry = input.nextInt())

因为当前循环仅在输入的数字是&lt; 0

所以循环具有语义(含义):

run while the entries are >= 0, read every time from the input to entry

当用户输入负数时,循环结束。

答案 1 :(得分:-1)

// add the values to your empty Array except the negative entries

看起来你也错过了一件小事。 你想要做的是:

if (entry >= 0){
  yolo.add(entry);
  sum += entry;
}

对于你的问题,我认为你声明的for循环是错误的,因为每次你调用input.nextInt()它都会要求一个新的输入,并且无论发生什么,你都可以第二次输出负值。

相关问题