在Java中使用while循环 [英] Using while loop in java

查看:217
本文介绍了在Java中使用while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读入并添加(仅)正整数,直到输入负整数.仅当输入负整数时程序才停止.我能想到的最好的方法是下面的代码,但是问题是,即使读取了负整数,它也不会停止. PS:我还在学习,所以请忍受我.我尝试将&& input2!<0添加到while循环条件中,但它作为错误出现.关于如何使其表现出自己想要的方式的任何建议?谢谢.

I'm trying to read in and add up (only) positive integers until a negative integer is entered. The program is supposed to stop only when a negative integer is entered. The best I've been able to come up with is the code below but the problem is it doesn't stop even when a negative integer is read. PS: I'm still learning so please bear with me. I've tried adding && input2!<0 to the while loop condition but it comes up as an error. Any suggestions as to how I can make it behave the way I want it to? Thanks.

public class Total{
    public static void main(String[] args){

            System.out.println("Enter an integer: ");

            Scanner entry = new Scanner(System.in);
            int input1 = entry.nextInt();

            System.out.println("Enter another integer: ");
            int input2 = entry.nextInt();

            int total = input1 + input2;

            while (input2 > 0){            
                System.out.println(total + "\nEnter another interger:  ");
                total += entry.nextInt();
            }
    }
}

推荐答案

您需要更改要测试的变量,这里是循环的 中的input2.否则就没有退出的机会.您在循环中所做的所有更改都是在input2保持不变的同时,总变量保持不变,因此每次测试时,它都保持> 0,这就是为什么您被卡住的原因.为什么不试一试,这次更改input2(并且仍然使用input2更改total),看看是否无法获得它.

You need to change the variable that is being tested, here input2, inside of the loop. Else there's no chance of exiting. All you change in the loop is the total variable while input2 remains unchanged, and so every time it is tested, it remains >0 and that's why you're stuck. Why not give it another try, this time changing input2 (and still changing total as well, using input2), and see if you can't get it.

这篇关于在Java中使用while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆