Java Loop Question. I'm supposed to write a program that reads in integers. When the sum is greater than or equal to 100, my program should display this by saying "Sum is now greater than or equal to 100" and stop. A sample session would go like this: Enter integer 50 Enter integer 40 Enter integer 9 Enter integer 5 Sum is now greater than or equal to 100
Essentially you'll want to initialize an integer, like int x = 0; and then use a while loop like this to help you cycle through. Try it out and play with it. while (x < 100) { //code here } Prompt the user to input an integer and add it to your current value with something like this: x = x + promptedInteger; and then after your while loop have it display the text you want. Good luck playing around, I hope that helps you get started.
I tried that but I need a little more specifics.
import java.util.Scanner; class labCd { public static void main(String[] args) { int x, sum; Scanner kb = new Scanner(System.in); System.out.println("Enter integer"); x = kb.nextInt(); sum = x + x + x + x; while (sum < 100) { System.out.println("Enter integer"); sum = x + x; } System.out.println("Sum is now greater than or equal to 100"); } } This is what I have so far.
Well I'm not sure why you have being set to equal 4 times the amount that was originally put in, you have everything you need to figure this problem out. I changed a couple things and made it slightly more clear ``` public class OpenStudy { public static void main(String[] args) { int x = 0; int sum = 0; Scanner scanner = new Scanner(System.in); while (sum < 100) { System.out.println("Enter integer"); x = scanner.nextInt(); sum += x; } System.out.println("Sum is now greater than or equal to 100"); } } ``` So the part `sum += x; ` is really just the same as `sum = sum + x;` only a shorter version of it. Try to follow this through as if you were the program and see how this works to understand and then you can apply your knowledge to further problems.
Also it's good practice to close your scanner when you're done with it. Here it's not a big deal, but in larger programs if you're done with it you really don't want that extra object hanging around being a memory leak. I'd probably put `scanner.close();` right after the while loop ends.
Thanks so much! It was actually much simpler than I thought it out to be!
Join our real-time social learning platform and learn together with your friends!